package com.cz.nongyetongv5.adapter.dao;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.bean.BeiJianDanWei;
import com.cz.nongyetongv5.bean.ChanPinJianCeRecord;
import com.cz.nongyetongv5.bean.ChanPinLeiBie;
import com.cz.nongyetongv5.bean.ChouYanJiGou;
import com.cz.nongyetongv5.bean.DuChaXunCha;
import com.cz.nongyetongv5.bean.JianCeFangFa;
import com.cz.nongyetongv5.bean.JianCeLeiBie;
import com.cz.nongyetongv5.bean.JianCeYiJu;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaHangYe;
import com.cz.nongyetongv5.bean.JianChaJieGuo;
import com.cz.nongyetongv5.bean.JianChaNeiRong;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.JianDuJianChaRecord;
import com.cz.nongyetongv5.bean.JianGuanDuiXiangFilter;
import com.cz.nongyetongv5.bean.LinkMan;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.bean.Plan;
import com.cz.nongyetongv5.bean.RenWuLaiYuan;
import com.cz.nongyetongv5.bean.Town;
import com.cz.nongyetongv5.bean.YangPin;
import com.cz.nongyetongv5.bean.YangPinBianHao;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.cz.nongyetongv5.utils.InitDataUtil;
import com.cz.nongyetongv5.utils.SerliazableUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 数据库访问的工具类,从系统继承过来
 */
public class DatabaseHelper extends SQLiteOpenHelper {

	private Context context = null;

	public DatabaseHelper(Context context, String name, CursorFactory factory,
						  int version) {
		super(context, name, factory, version);
		this.context = context;
		//	    getWritableDatabase().enableWriteAheadLogging();
	}

	// 第一次创建数据库的时候回调该方法,在这里我们可以进行建表的操作
	@Override
	public void onCreate(SQLiteDatabase db) {

		/**
		 * 创建市的表的SQL
		 */
		String cityTabeSql = context.getResources().getString(
				R.string.table_town_create);

		/**
		 * 被检单位表
		 */
		String beijiandanweiTabSql = context.getResources().getString(
				R.string.table_beijiandanwei);

		/**
		 * 检查单位
		 */
		String jianchadanweiTablSql = context.getResources().getString(
				R.string.table_jianchadanwei);

		/**
		 * 检查人员
		 */
		String jianguanrenyuanTabSql = context.getResources().getString(
				R.string.table_jianguanrenyuan);

		// 检查行业
		String jianchahangyeTabSql = context.getResources().getString(
				R.string.table_jianchahangye);

		/*
		 * 检查内容
		 */
		String jianchaneirongTabSql = context.getResources().getString(
				R.string.table_jianchaneirong);

		/**
		 * 检查记录
		 */
		String jianChaJiLuTabSql = context.getResources().getString(
				R.string.table_jianchajilu);

		/**
		 * 照片表的sql
		 */
		String photoTabSql = context.getResources().getString(
				R.string.table_photos);

		/**
		 * 任务来源表的sql
		 */
		String renwulaiyuanTabSql = context.getResources().getString(
				R.string.table_renwulaiyuan);

		/**
		 * 产品类别的Sql
		 */
		String chanpinleibieTabSql = context.getResources().getString(
				R.string.table_chanpinleibie);

		/**
		 * 检测类别表的sql
		 */
		String jianceleibieTabSql = context.getResources().getString(
				R.string.table_jianceleibie);

		/**
		 * 检测方法表的sql
		 */
		String jiancefangfaTabSql = context.getResources().getString(
				R.string.table_jiancefangfa);

		/**
		 * 检测依据表的sql
		 */
		String jianceyijuTabSql = context.getResources().getString(
				R.string.table_jianceyiju);

		/**
		 * 产品检测记录表
		 */
		String chanpinjiancerecordTabSql = context.getResources().getString(
				R.string.table_chapinjiancerecord);

		/**
		 * 样品表
		 */
		String yangpinTabSql = context.getResources().getString(
				R.string.table_yangpin);

		/**
		 * 产品检测照片信息表
		 */
		String chanpinjiancephotoTabSql = context.getResources().getString(
				R.string.table_chanpinjiance_photos);

		/**
		 * 抽验机构表
		 */
		String chouyanjigouTabSql = context.getResources().getString(
				R.string.table_chouyanjigou);

		/**
		 * 联系人
		 */
		String linkManSql = context.getResources().getString(
				R.string.table_linkman);
		/**
		 * 督察巡查
		 */
		String duchaxuecha = context.getResources().getString(
				R.string.table_duchaxuncha);
		// /**
		// * 用户头像表SQL
		// */
		// String touxiangTabSql = context.getResources().getString(
		// R.string.table_touxiang);

		// 执行建表SQL
		db.execSQL(cityTabeSql);

		db.execSQL(beijiandanweiTabSql);

		db.execSQL(jianchadanweiTablSql);

		db.execSQL(jianguanrenyuanTabSql);

		db.execSQL(jianchahangyeTabSql);

		db.execSQL(jianchaneirongTabSql);

		db.execSQL(jianChaJiLuTabSql);

		db.execSQL(photoTabSql);

		db.execSQL(renwulaiyuanTabSql);

		db.execSQL(chanpinleibieTabSql);

		db.execSQL(jianceleibieTabSql);

		db.execSQL(jiancefangfaTabSql);

		db.execSQL(jianceyijuTabSql);

		db.execSQL(chanpinjiancerecordTabSql);

		db.execSQL(yangpinTabSql);

		db.execSQL(chanpinjiancephotoTabSql);

		db.execSQL(chouyanjigouTabSql);

		db.execSQL(linkManSql);

		db.execSQL(duchaxuecha);

		// db.execSQL(touxiangTabSql);

		File appDataFile = ImageUtil.getThisAppDataFile();

		File jianDuJianChaDataFile = new File(appDataFile, "jiandujiancha");

		if (!jianDuJianChaDataFile.exists()) {

			jianDuJianChaDataFile.mkdirs();

		}

		File jianDuJianChaListDataFile = new File(jianDuJianChaDataFile, "list");

		if (!jianDuJianChaListDataFile.exists()) {
			jianDuJianChaListDataFile.mkdirs();
		}

		File chanPinJianCeDataFile = new File(appDataFile, "chanpinjiance");

		if (!chanPinJianCeDataFile.exists()) {

			chanPinJianCeDataFile.mkdirs();

		}

		File chanPinJianCeListDataFile = new File(chanPinJianCeDataFile, "list");

		if (!chanPinJianCeListDataFile.exists()) {
			chanPinJianCeListDataFile.mkdirs();
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		/*
		 * 数据库从1 升级到2
		 */
		if (newVersion >= 2 && oldVersion == 1) {

			// 1. 给 CHOUYANJIGOU 表增加TEL 字段

			db.beginTransaction();

			String sql = "ALTER TABLE CHOUYANJIGOU ADD COLUMN TEL VARCHAR(20) NULL ";

			db.execSQL(sql);

			// 2. 删除所有数据重新加载

			sql = "DELETE FROM CHOUYANJIGOU";

			db.execSQL(sql);

			db.setTransactionSuccessful();

			db.endTransaction();

			// 3. 重新加载数据
			InitDataUtil dataUtil = new InitDataUtil(this, context);
			/**
			 * 下载检验机构
			 */
			try {
				dataUtil.downloadChouYanJiGou(db);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		// 数据库升级 3,修改数据更新时间
		if (newVersion >= 3 && oldVersion == 2) {

			db.beginTransaction();

			ContentValues contentValues = new ContentValues();

			String time = "2014-01-01 00:00:00";

			contentValues.put("ADDTIME", time);

			contentValues.put("MODIFYTIME", time);

			contentValues.put("DELETETIME", time);

			// 更新
			db.update("BEIJIANDANWEI", contentValues, null, null);

			db.update("JIANCHADANWEI", contentValues, null, null);

			db.update("JIANGUANRENYUAN", contentValues, null, null);

			db.update("LINKMAN", contentValues, null, null);

			db.update("CHOUYANJIGOU", contentValues, null, null);

			db.update("DUCHAXUNCHA", contentValues, null, null);

			db.setTransactionSuccessful();

			db.endTransaction();
		}

		// 数据库升级 3,修改数据更新时间
		if (newVersion >= 4 && oldVersion == 3) {

			db.beginTransaction();

			ContentValues contentValues = new ContentValues();

			String time = "2014-01-01 00:00:00";

			contentValues.put("ADDTIME", time);

			contentValues.put("MODIFYTIME", time);

			contentValues.put("DELETETIME", time);

			// 更新
			db.update("BEIJIANDANWEI", contentValues, null, null);

			db.update("JIANCHADANWEI", contentValues, null, null);

			db.update("JIANGUANRENYUAN", contentValues, null, null);

			db.update("LINKMAN", contentValues, null, null);

			db.update("CHOUYANJIGOU", contentValues, null, null);

			db.update("DUCHAXUNCHA", contentValues, null, null);
			db.setTransactionSuccessful();

			db.endTransaction();
		}

		// 数据库升级 3,修改数据更新时间
		if (newVersion >= 5 && oldVersion == 4) {
			// 进行数据的恢复....

			SerliazableUtil.deleteAll();

			SerliazableUtil.deleteAllChanPinJianCe();

			// 数据分享
			SharedPreferences sharedData = context
					.getSharedPreferences(
							CommonConstants.SHARED_REFERENCES_TAG,
							Context.MODE_PRIVATE);

			String username = sharedData.getString("username", "");

			List<JianDuJianChaRecord> jianDuJianChaRecords = queryJianDuJianChaRecordByState(
					db, 0, username);

			if (jianDuJianChaRecords.size() > 0) {

				JianDuJianChaRecord jianDuJianChaRecord = jianDuJianChaRecords
						.get(0);
				jianDuJianChaRecord.setState(0);

				SerliazableUtil.saveTemp(jianDuJianChaRecord, username);

			}

			jianDuJianChaRecords = queryJianDuJianChaRecordByState(db, 1,
					username);

			if (jianDuJianChaRecords.size() > 0) {

				for (JianDuJianChaRecord jianDuJianChaRecord : jianDuJianChaRecords) {

					jianDuJianChaRecord.setState(1);
					SerliazableUtil.saveTemp(jianDuJianChaRecord, username);

				}

			}

			// ----------------------------------------------------------------------------

			List<ChanPinJianCeRecord> chanPinJianCeRecords = queryChanPinJianCeRecordByState(
					db, 0, username);

			if (chanPinJianCeRecords.size() > 0) {

				ChanPinJianCeRecord chanPinJianCeRecord = chanPinJianCeRecords
						.get(0);
				chanPinJianCeRecord.setState(0);

				SerliazableUtil.saveTemp(chanPinJianCeRecord, username);

			}

			chanPinJianCeRecords = queryChanPinJianCeRecordByState(db, 1,
					username);

			if (chanPinJianCeRecords.size() > 0) {

				for (ChanPinJianCeRecord chanPinJianCeRecord : chanPinJianCeRecords) {

					chanPinJianCeRecord.setState(1);

					SerliazableUtil.saveTemp(chanPinJianCeRecord, username);

				}

			}

		}

		if (newVersion >= 6 && oldVersion == 5) {

			File appDataFile = ImageUtil.getThisAppDataFile();

			File jianDuJianChaDataFile = new File(appDataFile, "jiandujiancha");

			if (!jianDuJianChaDataFile.exists()) {

				jianDuJianChaDataFile.mkdirs();

			}

			File jianDuJianChaListDataFile = new File(jianDuJianChaDataFile,
					"list");

			if (!jianDuJianChaListDataFile.exists()) {
				jianDuJianChaListDataFile.mkdirs();
			}

			File chanPinJianCeDataFile = new File(appDataFile, "chanpinjiance");

			if (!chanPinJianCeDataFile.exists()) {

				chanPinJianCeDataFile.mkdirs();

			}

			File chanPinJianCeListDataFile = new File(chanPinJianCeDataFile,
					"list");

			if (!chanPinJianCeListDataFile.exists()) {
				chanPinJianCeListDataFile.mkdirs();
			}

		}

		if (newVersion >= 7 && oldVersion == 6) {
			File appDataFile = ImageUtil.getThisAppDataFile();

			File jianDuJianChaDataFile = new File(appDataFile, "jiandujiancha");

			if (!jianDuJianChaDataFile.exists()) {

				jianDuJianChaDataFile.mkdirs();

			}

			File jianDuJianChaListDataFile = new File(jianDuJianChaDataFile,
					"list");

			if (!jianDuJianChaListDataFile.exists()) {
				jianDuJianChaListDataFile.mkdirs();
			}

			File chanPinJianCeDataFile = new File(appDataFile, "chanpinjiance");

			if (!chanPinJianCeDataFile.exists()) {

				chanPinJianCeDataFile.mkdirs();

			}

			File chanPinJianCeListDataFile = new File(chanPinJianCeDataFile,
					"list");

			if (!chanPinJianCeListDataFile.exists()) {
				chanPinJianCeListDataFile.mkdirs();
			}
		}

	}

	/**
	 * 插入一个Town
	 */
	public void insertTown(Town town) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("CODE", town.getCode());

		if (town.getParent_code() == null) {

			contentValues.putNull("PARENT_CODE");
		} else {
			contentValues.put("PARENT_CODE", town.getParent_code());
		}

		contentValues.put("NAME", town.getName());
		contentValues.put("MODIFY_TIME", town.getModify_time());

		db.insert("TOWN", null, contentValues);

	}

	/**
	 * 插入一个Town
	 */
	public void insertTown(List<Object> towns) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		/**
		 * 遍历所有Town
		 */
		for (Object townObj : towns) {

			if (townObj instanceof Town) {
				Town town = (Town) townObj;

				contentValues.put("CODE", town.getCode());

				if (town.getParent_code() == null) {

					contentValues.putNull("PARENT_CODE");
				} else {
					contentValues.put("PARENT_CODE", town.getParent_code());
				}

				contentValues.put("NAME", town.getName());
				contentValues.put("MODIFY_TIME", town.getModify_time());

				db.insert("TOWN", null, contentValues);
			}
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 查询出表中个数
	 *
	 * @return
	 */
	public int queryTableCount(String tableName) {

		Integer count = 0;

		String sql = "SELECT COUNT(*) FROM " + tableName;

		SQLiteDatabase db = getWritableDatabase();

		Cursor cursor = db.rawQuery(sql, null);

		if (cursor.moveToNext()) {

			count = cursor.getInt(0);

		}

		if (cursor != null) {
			cursor.close();
		}
		return count;
	}

	/**
	 * 清除表
	 */
	public void dropTableName(String name, Integer createTableSqlId) {

		SQLiteDatabase db = getWritableDatabase();

		String dropSql = "DROP TABLE IF EXISTS " + name;

		db.execSQL(dropSql);
		// 清除之后创建
		if (createTableSqlId != null) {
			String createTabSql = context.getResources().getString(
					createTableSqlId);
			db.execSQL(createTabSql);
		}

	}

	/**
	 * 插入被检单位
	 *
	 * @param beiJianDanWei
	 */
	public void insertBeiJianDanWei(BeiJianDanWei beiJianDanWei) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("ID", beiJianDanWei.getId());
		contentValues.put("NAME", beiJianDanWei.getName());
		contentValues.put("CODE", beiJianDanWei.getCode());
		contentValues.put("ADDRESS", beiJianDanWei.getAddress());
		contentValues.put("KIND", beiJianDanWei.getKind());
		contentValues.put("LONGITUDE", beiJianDanWei.getLongitude());
		contentValues.put("LATITUDE", beiJianDanWei.getLatitude());
		contentValues.put("CATEGORY", beiJianDanWei.getCategory());
		contentValues.put("CHARGE", beiJianDanWei.getCharge());
		contentValues.put("TEL", beiJianDanWei.getTel());
		contentValues.put("MOBILE", beiJianDanWei.getMobile());

		// contentValues.put("ADDTIME", beiJianDanWei.getAddTime());
		// contentValues.put("MODIFYTIME", beiJianDanWei.getModifyTime());
		// contentValues.put("DELETETIME", beiJianDanWei.getDeleteTime());

		if (CharsetUtil.isNotNull(beiJianDanWei.getAddTime())) {
			contentValues.put("ADDTIME", beiJianDanWei.getAddTime());
		}

		if (CharsetUtil.isNotNull(beiJianDanWei.getModifyTime())) {
			contentValues.put("MODIFYTIME", beiJianDanWei.getModifyTime());
		}

		if (CharsetUtil.isNotNull(beiJianDanWei.getDeleteTime())) {
			contentValues.put("DELETETIME", beiJianDanWei.getDeleteTime());
		}

		db.insert("BEIJIANDANWEI", null, contentValues);

	}

	/**
	 * 插入被检单位集合
	 *
	 * @param beiJianDanWeis
	 */
	public void insertBeiJianDanWei(List<Object> beiJianDanWeis) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (Object beiJianDanWeiObj : beiJianDanWeis) {
			contentValues.clear();

			if (beiJianDanWeiObj instanceof BeiJianDanWei) {

				contentValues.clear();

				BeiJianDanWei beiJianDanWei = (BeiJianDanWei) beiJianDanWeiObj;
				contentValues.put("ID", beiJianDanWei.getId());
				contentValues.put("NAME", beiJianDanWei.getName());
				contentValues.put("CODE", beiJianDanWei.getCode());
				contentValues.put("ADDRESS", beiJianDanWei.getAddress());
				contentValues.put("KIND", beiJianDanWei.getKind());
				contentValues.put("LONGITUDE", beiJianDanWei.getLongitude());
				contentValues.put("LATITUDE", beiJianDanWei.getLatitude());
				contentValues.put("CATEGORY", beiJianDanWei.getCategory());
				contentValues.put("CHARGE", beiJianDanWei.getCharge());
				contentValues.put("TEL", beiJianDanWei.getTel());
				contentValues.put("MOBILE", beiJianDanWei.getMobile());

				// contentValues.put("ADDTIME", beiJianDanWei.getAddTime());
				// contentValues.put("MODIFYTIME",
				// beiJianDanWei.getModifyTime());
				// contentValues.put("DELETETIME",
				// beiJianDanWei.getDeleteTime());

				if (CharsetUtil.isNotNull(beiJianDanWei.getAddTime())) {
					contentValues.put("ADDTIME", beiJianDanWei.getAddTime());
				}

				if (CharsetUtil.isNotNull(beiJianDanWei.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							beiJianDanWei.getModifyTime());
				}

				if (CharsetUtil.isNotNull(beiJianDanWei.getDeleteTime())) {
					contentValues.put("DELETETIME",
							beiJianDanWei.getDeleteTime());
				}

				db.insert("BEIJIANDANWEI", null, contentValues);

			}

		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 插入或者更新被检单位
	 *
	 * @param beiJianDanWeis
	 */
	public void insertOrUpdateBeiJianDanWei(List<BeiJianDanWei> beiJianDanWeis) {
		insertOrUpdateBeiJianDanWei(beiJianDanWeis,"");
	}
	public String insertOrUpdateBeiJianDanWei(List<BeiJianDanWei> beiJianDanWeis,String tablefix) {
		String back="none";
		Log.d("rafe count=",String.valueOf(beiJianDanWeis.size()));
		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		/**
		 * 遍历进行查询
		 */
		for (BeiJianDanWei beiJianDanWei : beiJianDanWeis) {

			String sql = "SELECT COUNT(*) FROM BEIJIANDANWEI"+tablefix+" WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { beiJianDanWei.getId() });
			int count=0;
			if (cursor.moveToNext())
				count = cursor.getInt(0);
			if (cursor != null) {
				cursor.close();
			}
			ContentValues contentValues = new ContentValues();
			contentValues.put("ID", beiJianDanWei.getId());
			contentValues.put("NAME", beiJianDanWei.getName());
			contentValues.put("CODE", beiJianDanWei.getCode());
			contentValues.put("ADDRESS", beiJianDanWei.getAddress());
			contentValues.put("KIND", beiJianDanWei.getKind());
			contentValues.put("LONGITUDE", beiJianDanWei.getLongitude());
			contentValues.put("LATITUDE", beiJianDanWei.getLatitude());
			contentValues.put("CATEGORY", beiJianDanWei.getCategory());
			contentValues.put("CHARGE", beiJianDanWei.getCharge());
			contentValues.put("TEL", beiJianDanWei.getTel());
			contentValues.put("MOBILE", beiJianDanWei.getMobile());

			if (CharsetUtil.isNotNull(beiJianDanWei.getAddTime())) {
				contentValues.put("ADDTIME", beiJianDanWei.getAddTime());
			}

			if (CharsetUtil.isNotNull(beiJianDanWei.getModifyTime())) {
				contentValues.put("MODIFYTIME",
						beiJianDanWei.getModifyTime());
			}

			if (CharsetUtil.isNotNull(beiJianDanWei.getDeleteTime())) {
				contentValues.put("DELETETIME",
						beiJianDanWei.getDeleteTime());
			}

			if (count> 0) {
				// 更新
				back="update";
				Log.d("rafe_sql_update","更新到BEIJIANDANWEI"+tablefix+"?"+beiJianDanWei.getId()+"??"+beiJianDanWei.getName());
				db.update("BEIJIANDANWEI"+tablefix, contentValues, "ID = ? ",
						new String[] { beiJianDanWei.getId() });
			} else {
				// 插入
				back="add";
				Log.d("rafe_sql_add","插入到BEIJIANDANWEI"+tablefix+"?"+beiJianDanWei.getId()+"??"+beiJianDanWei.getName());
				db.insert("BEIJIANDANWEI"+tablefix, null, contentValues);
			}

		}

		db.setTransactionSuccessful();

		db.endTransaction();
		return back;
	}

	/**
	 * 插入检查单位
	 *
	 * @param beiJianDanWei
	 */
	public void insertJianChaDanWei(JianChaDanWei jianChaDanWei) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.putNull("ID");
		contentValues.put("NAME", jianChaDanWei.getName());

		contentValues.put("CODE", jianChaDanWei.getCode());

		db.insert("JIANCHADANWEI", null, contentValues);
	}

	/**
	 * 插入检查单位
	 *
	 * @param beiJianDanWei
	 */
	public void insertJianChaDanWei(List<Object> jianChaDanWeis) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		/**
		 * 遍历所有检查单位
		 */
		for (Object jianChaDanWeiObj : jianChaDanWeis) {

			if (jianChaDanWeiObj instanceof JianChaDanWei) {

				contentValues.clear();
				JianChaDanWei jianchaDanWei = (JianChaDanWei) jianChaDanWeiObj;

				// 插入检查行业
				contentValues.put("ID", jianchaDanWei.getId());
				contentValues.put("NAME", jianchaDanWei.getName());
				contentValues.put("CODE", jianchaDanWei.getCode());

				// contentValues.put("ADDTIME", jianchaDanWei.getAddTime());
				// contentValues.put("MODIFYTIME",
				// jianchaDanWei.getModifyTime());
				// contentValues.put("DELETETIME",
				// jianchaDanWei.getDeleteTime());

				if (CharsetUtil.isNotNull(jianchaDanWei.getAddTime())) {
					contentValues.put("ADDTIME", jianchaDanWei.getAddTime());
				}

				if (CharsetUtil.isNotNull(jianchaDanWei.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							jianchaDanWei.getModifyTime());
				}

				if (CharsetUtil.isNotNull(jianchaDanWei.getDeleteTime())) {
					contentValues.put("DELETETIME",
							jianchaDanWei.getDeleteTime());
				}

				db.insert("JIANCHADANWEI", null, contentValues);
			}
		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 插入或者更新检查单位
	 *
	 * @param jianChaDanWeis
	 */
	public void insertOrUpdateJianChaDanWei(List<JianChaDanWei> jianChaDanWeis) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		/**
		 * 遍历所有检查单位
		 */
		for (JianChaDanWei jianChaDanWeiObj : jianChaDanWeis) {

			String sql = "SELECT COUNT(*) FROM JIANCHADANWEI WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { jianChaDanWeiObj.getId() });

			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();

				JianChaDanWei jianchaDanWei = (JianChaDanWei) jianChaDanWeiObj;

				// 插入检查行业
				contentValues.put("ID", jianchaDanWei.getId());
				contentValues.put("NAME", jianchaDanWei.getName());
				contentValues.put("CODE", jianchaDanWei.getCode());

				if (CharsetUtil.isNotNull(jianchaDanWei.getAddTime())) {
					contentValues.put("ADDTIME", jianchaDanWei.getAddTime());
				}

				if (CharsetUtil.isNotNull(jianchaDanWei.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							jianchaDanWei.getModifyTime());
				}

				if (CharsetUtil.isNotNull(jianchaDanWei.getDeleteTime())) {
					contentValues.put("DELETETIME",
							jianchaDanWei.getDeleteTime());
				}

				if (count > 0) {
					// 更新
					db.update("JIANCHADANWEI", contentValues, " ID = ? ",
							new String[] { jianchaDanWei.getId() });

				} else {
					// 插入
					db.insert("JIANCHADANWEI", null, contentValues);
				}

			}

			if (cursor != null)
				cursor.close();

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 插入检查人员
	 *
	 * @param beiJianDanWei
	 */
	public void insertJianChaRenYuan(JianChaRenYuan jianChaRenYuan) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("ID", jianChaRenYuan.getId());
		contentValues.put("NAME", jianChaRenYuan.getName());
		contentValues.put("RANK", jianChaRenYuan.getRank());
		contentValues.put("CODE", jianChaRenYuan.getCode());

		db.insert("JIANGUANRENYUAN", null, contentValues);
	}

	/**
	 * 插入检查人员
	 *
	 * @param beiJianDanWei
	 */
	public void insertJianChaRenYuan(List<Object> jianChaRenYuans) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		ContentValues contentValues = new ContentValues();

		/**
		 * 遍历所有检查人员
		 */
		for (Object jianChaRenYuanObj : jianChaRenYuans) {

			if (jianChaRenYuanObj instanceof JianChaRenYuan) {
				JianChaRenYuan jianChaRenYuan = (JianChaRenYuan) jianChaRenYuanObj;

				if (jianChaRenYuan.getRank() == 3) {

					contentValues.clear();

					// 插入检查人员
					contentValues.put("ID", jianChaRenYuan.getId());
					contentValues.put("NAME", jianChaRenYuan.getName());
					contentValues.put("RANK", jianChaRenYuan.getRank());
					contentValues.put("CODE", jianChaRenYuan.getCode());
					// contentValues.put("ADDTIME",
					// jianChaRenYuan.getAddTime());
					// contentValues.put("MODIFYTIME",
					// jianChaRenYuan.getModifyTime());
					// contentValues.put("DELETETIME",
					// jianChaRenYuan.getDeleteTime());

					if (CharsetUtil.isNotNull(jianChaRenYuan.getAddTime())) {
						contentValues.put("ADDTIME",
								jianChaRenYuan.getAddTime());
					}

					if (CharsetUtil.isNotNull(jianChaRenYuan.getModifyTime())) {
						contentValues.put("MODIFYTIME",
								jianChaRenYuan.getModifyTime());
					}

					if (CharsetUtil.isNotNull(jianChaRenYuan.getDeleteTime())) {
						contentValues.put("DELETETIME",
								jianChaRenYuan.getDeleteTime());
					}

					db.insert("JIANGUANRENYUAN", null, contentValues);
				}
			}
		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 插入和更新检察人员
	 *
	 * @param jianChaRenYuan
	 */
	public void insertOrUpdateJianChaRenYuan(
			List<JianChaRenYuan> jianChaRenYuans) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		for (JianChaRenYuan jianChaRenYuan : jianChaRenYuans) {

			String sql = "SELECT COUNT(*) FROM JIANGUANRENYUAN WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { jianChaRenYuan.getId() });

			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();

				// 插入检查人员
				contentValues.put("ID", jianChaRenYuan.getId());
				contentValues.put("NAME", jianChaRenYuan.getName());
				contentValues.put("RANK", jianChaRenYuan.getRank());
				contentValues.put("CODE", jianChaRenYuan.getCode());
				// contentValues.put("ADDTIME", jianChaRenYuan.getAddTime());
				// contentValues.put("MODIFYTIME",
				// jianChaRenYuan.getModifyTime());
				// contentValues.put("DELETETIME",
				// jianChaRenYuan.getDeleteTime());

				if (CharsetUtil.isNotNull(jianChaRenYuan.getAddTime())) {
					contentValues.put("ADDTIME", jianChaRenYuan.getAddTime());
				}

				if (CharsetUtil.isNotNull(jianChaRenYuan.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							jianChaRenYuan.getModifyTime());
				}

				if (CharsetUtil.isNotNull(jianChaRenYuan.getDeleteTime())) {
					contentValues.put("DELETETIME",
							jianChaRenYuan.getDeleteTime());
				}

				if (count > 0) {
					// 更新
					db.update("JIANGUANRENYUAN", contentValues, "ID = ? ",
							new String[] { jianChaRenYuan.getId() });

				} else {
					// 插入
					db.insert("JIANGUANRENYUAN", null, contentValues);
				}
			}

			if (cursor != null)
				cursor.close();
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 插入检查行业
	 */
	public void insertJianChaHangYe(JianChaHangYe jianChaHangYe) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("ID", jianChaHangYe.getId());
		contentValues.put("NAME", jianChaHangYe.getName());

		db.insert("JIANCHAHANGYE", null, contentValues);

	}

	/**
	 * 插入检查行业
	 */
	public void insertJianChaHangYe(List<Object> jianChaHangYes) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		/**
		 * 遍历所有检查行业
		 */
		for (Object jianChaHangYeObj : jianChaHangYes) {

			if (jianChaHangYeObj instanceof JianChaHangYe) {
				JianChaHangYe jianChaHangYe = (JianChaHangYe) jianChaHangYeObj;

				contentValues.clear();

				contentValues.put("ID", jianChaHangYe.getId());
				contentValues.put("NAME", jianChaHangYe.getName());

				db.insert("JIANCHAHANGYE", null, contentValues);

			}
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 插入检查内容
	 */
	public void insertJianChaNeiRong(JianChaNeiRong jianChaNeiRong) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("ID", jianChaNeiRong.getId());
		contentValues.put("NAME", jianChaNeiRong.getName());

		db.insert("JIANCHANEIRONG", null, contentValues);

	}

	/**
	 * 插入检查内容
	 */
	public void insertJianChaNeiRong(List<Object> jianChaNeiRongs) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		/**
		 * 遍历所有检查内容
		 */
		for (Object jianChaNeiRongObj : jianChaNeiRongs) {
			contentValues.clear();

			if (jianChaNeiRongObj instanceof JianChaNeiRong) {
				JianChaNeiRong jianChaNeiRong = (JianChaNeiRong) jianChaNeiRongObj;
				contentValues.put("ID", jianChaNeiRong.getId());
				contentValues.put("NAME", jianChaNeiRong.getName());

				db.insert("JIANCHANEIRONG", null, contentValues);
			}
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 查询所有检查内容
	 *
	 * @return
	 */
	public List<JianChaNeiRong> queryAllJianChaNeiRong() {

		List<JianChaNeiRong> jianChaNeiRongs = new ArrayList<JianChaNeiRong>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM JIANCHANEIRONG ", null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			jianChaNeiRongs.add(new JianChaNeiRong(id, name));
		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaNeiRongs;
	}

	/**
	 * 查询检查内容根据ID
	 *
	 * @return
	 */
	public JianChaNeiRong queryJianChaNeiRongById(String id) {

		JianChaNeiRong chaNeiRong = null;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT * FROM JIANCHANEIRONG WHERE ID = ?",
				new String[] { id });

		if (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			chaNeiRong = new JianChaNeiRong(Integer.parseInt(id), name);
		}

		if (cursor != null) {
			cursor.close();
		}

		return chaNeiRong;
	}

	/**
	 * 根据父亲ID查询出TOWN
	 *
	 * @param parent
	 * @return
	 */
	public List<Town> queryTownByParent(String parent) {
		return queryTownByParent(parent,0);
	}
	public List<Town> queryTownByParent(String parent,int page) {

		List<Town> towns = new ArrayList<Town>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = null;

		if (parent == null) {
			//xrf
			cursor = db.rawQuery(
					"SELECT * FROM TOWN T WHERE T.PARENT_CODE IS NULL ", null);
			Log.d("sql2","SELECT * FROM TOWN T WHERE T.PARENT_CODE IS NULL limit "+(page*SPAN)+","+SPAN);
		} else {
			cursor = db.rawQuery(
					"SELECT * FROM TOWN T WHERE T.PARENT_CODE = ? ",
					new String[] { parent.toString() });
			Log.d("sql2","SELECT * FROM TOWN T WHERE T.PARENT_CODE = ? "+(page*SPAN));
		}

		while (cursor.moveToNext()) {

			String code = cursor.getString(cursor.getColumnIndex("CODE"));

			String parent_code = cursor.getString(cursor
					.getColumnIndex("PARENT_CODE"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			String modify_time = cursor.getString(cursor
					.getColumnIndex("MODIFY_TIME"));
			Town t=new Town(code, parent_code, name, modify_time);
			try{
				t.setBeijiandanwei(cursor.getInt(cursor
						.getColumnIndex("CNT")));
			}catch(java.lang.Exception e){

				t.setBeijiandanwei(0);
			}
			towns.add(t);
		}

		if (cursor != null) {
			cursor.close();
		}
		Log.d("sql2","complele");
		return towns;
	}
	public void insertOrUpdateSync(String code,String field,String time) {

		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		ContentValues contentValues = new ContentValues();
		contentValues.put(field,time);
		Log.d("rafe_sync_update","更新到"+code+">>"+field+">>"+time);
		db.update("BEIJIANDANWEI_SYN", contentValues, "CODE = ? ",
				new String[] { code});
		db.setTransactionSuccessful();
		db.endTransaction();

	}
	public JSONArray querySyncOther(String code) {
		JSONArray data=new JSONArray();
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor  = db.rawQuery(
				"SELECT * FROM MOBILE_SYN   WHERE CODE ='"+code+"' ",
				new String[] {});


		while (cursor.moveToNext()) {
			JSONObject da=new JSONObject();
			try {
				da.putOpt("code", cursor.getString(cursor.getColumnIndex("CODE")));
				da.putOpt("ent_add_time", cursor.getString(cursor.getColumnIndex("ENT_ADDTIME")));
				da.putOpt("ent_modify_time", cursor.getString(cursor.getColumnIndex("ENT_MODIFYTIME")));

				da.putOpt("ent_delete_time", cursor.getString(cursor.getColumnIndex("ENT_DELETETIME")));

				da.putOpt("department_add_time", cursor.getString(cursor.getColumnIndex("DEPART_ADDTIME")));
				da.putOpt("department_modify_time", cursor.getString(cursor.getColumnIndex("DEPART_MODIFYTIME")));
				da.putOpt("department_delete_time", cursor.getString(cursor.getColumnIndex("DEPART_DELETETIME")));
				da.putOpt("detector_add_time", cursor.getString(cursor.getColumnIndex("DETECTOR_ADDTIME")));
				da.putOpt("detector_modify_time", cursor.getString(cursor.getColumnIndex("DETECTOR_MODIFYTIME")));
				da.putOpt("detector_delete_time", cursor.getString(cursor.getColumnIndex("DETECTOR_DELETETIME")));
				da.putOpt("team_add_time", cursor.getString(cursor.getColumnIndex("TEAM_ADDTIME")));
				da.putOpt("team_modify_time", cursor.getString(cursor.getColumnIndex("TEAM_MODIFYTIME")));
				da.putOpt("team_delete_time", cursor.getString(cursor.getColumnIndex("TEAM_DELETETIME")));
				da.putOpt("linkman_add_time", cursor.getString(cursor.getColumnIndex("LINKMAN_ADDTIME")));
				da.putOpt("linkman_modify_time", cursor.getString(cursor.getColumnIndex("LINKMAN_MODIFYTIME")));
				da.putOpt("linkman_delete_time", cursor.getString(cursor.getColumnIndex("LINKMAN_DELETETIME")));

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			data.put(da);
		}

		if (cursor != null) {
			cursor.close();
		}
		return data;
	}
	public JSONArray querySyncByParent(String code) {
		JSONArray data=new JSONArray();
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor  = db.rawQuery(
				"SELECT * FROM BEIJIANDANWEI_SYN   WHERE CODE LIKE '"+code+"%' ",
				new String[] {});

		while (cursor.moveToNext()) {
			JSONObject da=new JSONObject();
			try {
				da.putOpt("code", cursor.getString(cursor.getColumnIndex("CODE")));

				da.putOpt("add_time", cursor.getString(cursor.getColumnIndex("ADDTIME")));
				da.putOpt("modify_time", cursor.getString(cursor.getColumnIndex("MODIFYTIME")));
				da.putOpt("delete_time", cursor.getString(cursor.getColumnIndex("DELETETIME")));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			data.put(da);
		}

		if (cursor != null) {
			cursor.close();
		}
		return data;
	}
	public JSONObject querySyncByCode(String code) {
		JSONObject data=null;
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor  = db.rawQuery(
				"SELECT * FROM BEIJIANDANWEI_SYN   WHERE CODE =? ",
				new String[] {code});


		if (cursor.moveToNext()) {
			data=new JSONObject();
			try {
				data.putOpt("code", cursor.getString(cursor.getColumnIndex("CODE")));
				data.putOpt("add_time", cursor.getString(cursor.getColumnIndex("ADDTIME")));
				data.putOpt("modify_time", cursor.getString(cursor.getColumnIndex("MODIFYTIME")));
				data.putOpt("delete_time", cursor.getString(cursor.getColumnIndex("DELETETIME")));
			}catch(java.lang.Exception e){
				data= null;
			}
		}

		if (cursor != null) {
			cursor.close();
		}
		return data;
	}

	public List<Town> queryTownByWhere(String where) {

		List<Town> towns = new ArrayList<Town>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = null;


		cursor = db.rawQuery(
				"SELECT * FROM TOWN WHERE "+where ,
				new String[] {});


		while (cursor.moveToNext()) {

			String code = cursor.getString(cursor.getColumnIndex("CODE"));

			String parent_code = cursor.getString(cursor
					.getColumnIndex("PARENT_CODE"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			String modify_time = cursor.getString(cursor
					.getColumnIndex("MODIFY_TIME"));
			Town t=new Town(code, parent_code, name, modify_time);
			try{
				t.setBeijiandanwei(cursor.getInt(cursor
						.getColumnIndex("CNT")));
			}catch(java.lang.Exception e){

				t.setBeijiandanwei(0);
			}
			towns.add(t);
		}

		if (cursor != null) {
			cursor.close();
		}
		return towns;
	}

	public void create(String sql){

		SQLiteDatabase db = getReadableDatabase();
		db.execSQL(sql);

	}
	public boolean hasTable(String table){

		boolean result=false;
		String sql ="select count(*) as c from sqlite_master where type ='table' and name ='"+table+"'";
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor =db.rawQuery(sql, null);
		if(cursor.moveToNext()){
			int count = cursor.getInt(0);
			if(count>0){
				result = true;
			}
		}
		return result;
	}
	public List<Town> queryTownByCode(String regcode) {

		List<Town> towns = new ArrayList<Town>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor  = db.rawQuery(
				"select * from TOWN where length(code)=8 and code like '"+regcode+"%'",
				new String[] {  });
		while (cursor.moveToNext()) {

			String code = cursor.getString(cursor.getColumnIndex("CODE"));

			String parent_code = cursor.getString(cursor
					.getColumnIndex("PARENT_CODE"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			String modify_time = cursor.getString(cursor
					.getColumnIndex("MODIFY_TIME"));
			Town t=new Town(code, parent_code, name, modify_time);
			try{
				t.setBeijiandanwei(cursor.getInt(cursor
						.getColumnIndex("CNT")));
			}catch(java.lang.Exception e){

				t.setBeijiandanwei(0);
			}
			towns.add(t);
		}

		if (cursor != null) {
			cursor.close();
		}
		Log.d("sql2","complele");
		return towns;
	}

	/**
	 * 根据父亲ID查询出TOWN
	 *
	 * @param parent
	 * @return
	 */
	public    Town queryTownById(String id) {

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM TOWN T WHERE T.CODE = ?",
				new String[] { id + "" });

		Town town = null;
		if (cursor.moveToNext()) {
			String code = cursor.getString(cursor.getColumnIndex("CODE"));
			String parent_code = cursor.getString(cursor
					.getColumnIndex("PARENT_CODE"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			String modify_time = cursor.getString(cursor
					.getColumnIndex("MODIFY_TIME"));

			town = new Town(code, parent_code, name, modify_time);
			try{
				town.setBeijiandanwei(cursor.getInt(cursor
						.getColumnIndex("CNT")));
			}catch(java.lang.Exception e){
				town.setBeijiandanwei(0);
			}
		}

		if (cursor != null) {
			cursor.close();
		}

		return town;
	}

	/**
	 * 查询所有联系人根据乡镇信息
	 *
	 * @param townId
	 * @param datas
	 */
	public List<LinkMan> queryLinkManByTownId(String townId, int category) {

		List<LinkMan> linkMains = new ArrayList<LinkMan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM LINKMAN L WHERE L.REGION_CODE = ? AND L.RANK = ?",
						new String[] { townId + "", category + "" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String realName = cursor.getString(cursor
					.getColumnIndex("REALNAME"));

			Integer sex = cursor.getInt(cursor.getColumnIndex("SEX"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String departmentName = cursor.getString(cursor
					.getColumnIndex("DEPARTMENT_NAME"));

			String post = cursor.getString(cursor.getColumnIndex("POST"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			Double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			Double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String regionCode = cursor.getString(cursor
					.getColumnIndex("LATITUDE"));

			LinkMan linkMan = new LinkMan(id, realName, sex, tel, mobile,
					departmentName, post, rank, longitude, latitude,
					regionCode, null, null, null);
			;

			linkMains.add(linkMan);
		}

		if (cursor != null) {
			cursor.close();
		}

		return linkMains;
	}

	/**
	 * 查询所有联系人根据乡镇信息
	 *
	 * @param townId
	 * @param datas
	 */
	public List<LinkMan> queryLinkManByFilter(String code, String filter) {

		List<LinkMan> linkMains = new ArrayList<LinkMan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM LINKMAN L WHERE REGION_CODE||'' LIKE '"
								+ code
								+ "%' AND ( L.TEL LIKE ? OR L.MOBILE LIKE ? OR L.REALNAME LIKE ? )",
						new String[] { "%" + filter + "%", "%" + filter + "%",
								"%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String realName = cursor.getString(cursor
					.getColumnIndex("REALNAME"));

			Integer sex = cursor.getInt(cursor.getColumnIndex("SEX"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String departmentName = cursor.getString(cursor
					.getColumnIndex("DEPARTMENT_NAME"));

			String post = cursor.getString(cursor.getColumnIndex("POST"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			Double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			Double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String regionCode = cursor.getString(cursor
					.getColumnIndex("REGION_CODE"));

			LinkMan linkMan = new LinkMan(id, realName, sex, tel, mobile,
					departmentName, post, rank, longitude, latitude,
					regionCode, null, null, null);
			;

			linkMains.add(linkMan);
		}

		if (cursor != null) {
			cursor.close();
		}

		return linkMains;
	}

	/**
	 * 查询所有的联系人根据地址
	 *
	 * @param townId
	 * @return
	 */
	public int queryLinkManCountByTownId(String townId, int category) {

		int count = 0;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT COUNT(*) FROM LINKMAN L WHERE L.RANK = ?  AND CAST(L.REGION_CODE AS VARCHAR) LIKE ?",
						new String[] { category + "", townId + "%" });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;
	}

	/**
	 * 查询出直属检查单位
	 *
	 * @param code
	 * @return
	 */
	public List<JianChaDanWei> queryAllJianChaDanWeiNotLike(String code) {

		List<JianChaDanWei> jianChaDanWeis = new ArrayList<JianChaDanWei>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM JIANCHADANWEI WHERE  CODE  = ? ORDER BY CODE ASC",
						new String[] { code });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaDanWeis.add(new JianChaDanWei(id, name, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}
		return jianChaDanWeis;
	}

	/**
	 * 查询出所有检查单位
	 */
	public List<JianChaDanWei> queryAllJianChaDanWei(String code) {

		List<JianChaDanWei> jianChaDanWeis = new ArrayList<JianChaDanWei>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,CODE FROM ( SELECT ID,NAME ,CODE FROM JIANCHADANWEI WHERE CODE = ? ORDER BY CODE ASC   ) UNION ALL SELECT ID,NAME,CODE FROM (SELECT  ID,NAME ,CODE  FROM JIANCHADANWEI WHERE CODE <> ?  AND CODE LIKE ? ORDER BY CODE ASC )",
						new String[] { code, code, code + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaDanWeis.add(new JianChaDanWei(id, name, codeVal));

		}

		jianChaDanWeis.get(0).setAllowRemove(false);

		if (cursor != null) {
			cursor.close();
		}
		return jianChaDanWeis;
	}

	/**
	 * 根据名称过滤被检单位
	 *
	 * @param filter
	 * @return
	 */
	public List<JianChaDanWei> queryAllJianChaDanWei(String code, String filter) {

		List<JianChaDanWei> jianChaDanWeis = new ArrayList<JianChaDanWei>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,CODE FROM ( SELECT ID,NAME ,CODE FROM JIANCHADANWEI WHERE CODE = ? AND NAME LIKE ?  ORDER BY CODE ASC   ) UNION ALL SELECT ID,NAME,CODE FROM (SELECT  ID,NAME ,CODE  FROM JIANCHADANWEI WHERE CODE <> ?  AND CODE LIKE ? AND NAME LIKE ? ORDER BY CODE ASC )",
						new String[] { code, "%" + filter + "%", code,
								code + "%", "%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaDanWeis.add(new JianChaDanWei(id, name, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaDanWeis;
	}

	/**
	 * 查询出所有被检单位
	 */
	public List<BeiJianDanWei> queryAllBeiJianDanWieByFilter(String code,
															 String filter,int page) {

		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();

		SQLiteDatabase db = getReadableDatabase();

		String sql = "SELECT * FROM BEIJIANDANWEI WHERE CODE||'' LIKE '" + code
				+ "%' AND ( CHARGE LIKE ? OR NAME LIKE ?  ) ";
		sql+=" limit "+(page*SPAN)+","+SPAN;

		Log.d("Sql3",sql);

		Cursor cursor = db.rawQuery(sql, new String[] { "%" + filter + "%",
				"%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;

	}

	/**
	 * 查询出所有被检单位
	 */
	/**
	 * 查询出所有被检单位
	 */
	public List<BeiJianDanWei> queryAllBeiJianDanWie(String code,
													 JianGuanDuiXiangFilter filter) {
		return this.queryAllBeiJianDanWie(code,filter,0,null,null);
	}
	public List<BeiJianDanWei> queryAllBeiJianDanWie(String code,
													 JianGuanDuiXiangFilter filter,int page,String lx,String hy) {

		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();
		String table="BEIJIANDANWEI"+code;
		if(code.length()>8){
			table="BEIJIANDANWEI"+code.substring(0, 8);
		}

		SQLiteDatabase db = getReadableDatabase();

		String sql = "select B.*,TOWN.NAME as 'regionname' from "+table+" B LEFT JOIN TOWN on TOWN.CODE=B.CODE  ";

		if (CharsetUtil.isNotNull(code)&&filter.isAll()) {
			sql += "WHERE B.CODE =  '" + code + "'";
		}else{
			sql += "WHERE B.CODE like  '3204%'";
		}



		if (filter != null && filter.getIds().size() > 0) {
			Log.d("rafealarm","检索报警");
			// 如果没有Where 说明第一个code 没有添加
			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";
			} else {
				sql += " AND ";
			}

			sql += "ID IN (";

			for (String id : filter.getIds()) {

				sql += "'" + id + "'";

				if (filter.getIds().indexOf(id) != filter.getIds().size() - 1) {

					sql += ",";
				} else {
					sql += ")";
				}

			}
			sql+=" AND B.code='"+code+"'";

		}

		// 如果没有Where 说明第一个code 没有添加
		if ((filter != null && filter.getKinds().size() > 0)) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "KIND IN ( ";

			for (int kind : filter.getKinds()) {

				sql += kind;

				if (filter.getKinds().indexOf(kind) != filter.getKinds().size() - 1) {

					sql += ",";
				} else {
					sql += ")  ";
				}
			}

		}

		if (filter != null && filter.getCategory().size() > 0) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "(";

			for (int category : filter.getCategory()) {
				sql += " CATEGORY LIKE '%" + category + "%'  ";

				if (filter.getCategory().indexOf(category) != filter
						.getCategory().size() - 1) {

					sql += "OR ";
				}
			}

			sql += ")";

		}
		/**xrf*/

		if(lx!=null)
			sql+=" and B.kind="+lx;
		if(hy!=null)
			sql+=" and B.categroy="+hy;

		sql+=" order by B.code ";
		sql+=" limit "+(page*SPAN)+","+SPAN;

		Log.d("rafeall",sql);
		Cursor cursor = db.rawQuery(sql, new String[] {});

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));
			BeiJianDanWei danwei=new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile);
			danwei.setRegionName(cursor.getString(cursor.getColumnIndex("regionname")));
			beiJianDanWeis.add(danwei);

		}

		if (cursor != null) {
			cursor.close();
		}
		return beiJianDanWeis;
	}

	/**
	 * 查询出所有被检单位
	 */
	public List<BeiJianDanWei> queryAllBeiJianDanWieAndChild(String code,
															 JianGuanDuiXiangFilter filter) {

		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();

		SQLiteDatabase db = getReadableDatabase();

		String sql = "SELECT * FROM BEIJIANDANWEI  ";

		if (CharsetUtil.isNotNull(code)) {
			sql += "WHERE CODE >=  '" + code + "'";
		}

		if (filter != null && filter.getIds().size() > 0) {

			// 如果没有Where 说明第一个code 没有添加
			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND ";
			}

			sql += "ID IN (";

			for (String id : filter.getIds()) {

				sql += "'" + id + "'";

				if (filter.getIds().indexOf(id) != filter.getIds().size() - 1) {

					sql += ",";
				} else {
					sql += ")";
				}

			}

		}

		// 如果没有Where 说明第一个code 没有添加
		if ((filter != null && filter.getKinds().size() > 0)) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "KIND IN ( ";

			for (int kind : filter.getKinds()) {

				sql += kind;

				if (filter.getKinds().indexOf(kind) != filter.getKinds().size() - 1) {

					sql += ",";
				} else {
					sql += ")  ";
				}
			}

		}

		if (filter != null && filter.getCategory().size() > 0) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "(";

			for (int category : filter.getCategory()) {
				sql += " CATEGORY LIKE '%" + category + "%'  ";

				if (filter.getCategory().indexOf(category) != filter
						.getCategory().size() - 1) {

					sql += "OR ";
				}
			}

			sql += ")";



		}

		Cursor cursor = db.rawQuery(sql, new String[] {});

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}

	/**
	 * 根据名字查询出被检单位的数量
	 */
	public int queryCountBeiJianDanWeiByName(String name,String code) {
		if(code==null)return 0;
		if(code.length()<8){return 0;}
		else code=code.substring(0, 8);
		int count = 0;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT COUNT(*) FROM BEIJIANDANWEI"+code+"  WHERE NAME = ? ",
				new String[] { name });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;

	}
	public    BeiJianDanWei queryBeiJianDanWie(String id) {

		BeiJianDanWei beiJianDanWei = null;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT * FROM BEIJIANDANWEI BJDW WHERE BJDW.ID = ? " , new String[] { id });

		if (cursor.moveToNext()) {

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWei = new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile);
		}

		if (cursor != null) {
			cursor.close();

		}


		return beiJianDanWei;
	}
	public    BeiJianDanWei queryBeiJianDanWie2(String id, String code) {

		BeiJianDanWei beiJianDanWei = null;

		SQLiteDatabase db = getReadableDatabase();
		if(code.length()>8)code=code.substring(0, 8);
		Cursor cursor = db.rawQuery(
				"SELECT * FROM BEIJIANDANWEI"+code+" BJDW WHERE BJDW.ID = ? AND BJDW.CODE LIKE '"
						+ code + "%'", new String[] { id });

		if (cursor.moveToNext()) {

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWei = new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile);
		}

		if (cursor != null) {
			cursor.close();

		}


		return beiJianDanWei;
	}
	public    BeiJianDanWei queryBeiJianDanWie(String id, String code) {

		BeiJianDanWei beiJianDanWei = null;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT * FROM BEIJIANDANWEI BJDW WHERE BJDW.ID = ? AND BJDW.CODE LIKE '"
						+ code + "%'", new String[] { id });

		if (cursor.moveToNext()) {

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWei = new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile);
		}

		if (cursor != null) {
			cursor.close();

		}


		return beiJianDanWei;
	}
	public List<BeiJianDanWei> queryAllBeiJianDanWie(String code) {
		return queryAllBeiJianDanWie(code,0,null,null);
	}

	//是否为空表
	public boolean isEmpty(String tableName) {



		SQLiteDatabase db = getReadableDatabase();



		String sql="SELECT * FROM  "+tableName+" limit 0,3 ";


		Cursor cursor = db.rawQuery(
				sql,
				new String[] {});

		boolean back=cursor.moveToNext();
		if (cursor != null) {
			cursor.close();
		}

		return !back;
	}

	public List<BeiJianDanWei> queryAllBeiJianDanWie(String code,int page,String lx,String hy) {

		Log.d("rafecode",String.valueOf(code));

		SQLiteDatabase db = getReadableDatabase();

		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();
		if(code.length()<8){return beiJianDanWeis;  }
		String tableCode=code.substring(0,8);
		Log.d("rafecode","BEIJIANDANWEI"+tableCode);
		if(!hasTable("BEIJIANDANWEI"+tableCode)){

			Log.d("rafecode","没有BEIJIANDANWEI"+tableCode);
			return beiJianDanWeis;
		}



		String sql="SELECT * FROM BEIJIANDANWEI"+tableCode+" BJDW WHERE BJDW.CODE LIKE ? ";

		if(lx!=null){
			sql+=lx;
		}
		if(hy!=null){
			sql+=hy;
		}
		sql+=" LIMIT "+(page*SPAN)+","+SPAN;
		Cursor cursor = db.rawQuery(
				sql,
				new String[] { code + "%" });


		Log.d("rafe sql beijiandanwei222",sql+"?"+code);

		Log.d("sql",sql);
		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}

	/**
	 * 根据名称过滤被检单位
	 *
	 * @param filter
	 * @return
	 */
	public static final int SPAN=20;
	public List<BeiJianDanWei> queryAllBeiJianDanWie(String filter, String code) {
		return queryAllBeiJianDanWie(filter,code,0,null,null);
	}
	public List<BeiJianDanWei> queryAllBeiJianDanWie(String filter, String code,int page,String lx,String hy) {



		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();
		if(code.length()<8){return beiJianDanWeis;
		}
		String tableCode=code.substring(0,8);
		SQLiteDatabase db = getReadableDatabase();
		if(!hasTable("BEIJIANDANWEI"+tableCode)){
			return beiJianDanWeis;
		}
		String sql="SELECT * FROM BEIJIANDANWEI"+tableCode+" BJDW WHERE BJDW.CODE LIKE ? AND  BJDW.NAME LIKE ?";
		if(lx!=null)
			sql+=lx;
		if(hy!=null)
			sql+=hy;
		Log.d("sqlhy",sql);
		sql+=" limit "+(page*SPAN)+","+SPAN;

		Log.d("rafe sql beijiandanwei",sql+"?code="+code);
		Log.d("sql",sql);
		Cursor cursor = db
				.rawQuery(sql,new String[] { code + "%", "%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}

	/**
	 * 查询检查人员
	 *
	 * @param code
	 * @return
	 */
	public List<JianChaRenYuan> queryAllJianChaRenYuanNotLike(String code,
															  String name) {

		List<JianChaRenYuan> jianChaRenYuans = new ArrayList<JianChaRenYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM JIANGUANRENYUAN WHERE CODE =  ? AND NAME = ? ORDER BY CODE ASC ",
						new String[] { code, name });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			name = cursor.getString(cursor.getColumnIndex("NAME"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaRenYuans.add(new JianChaRenYuan(id, name, rank, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaRenYuans;
	}

	/**
	 * 查询检查人员 只要查RANK是3的人员
	 *
	 * @param code
	 * @return
	 */
	public List<JianChaRenYuan> queryAllJianChaRenYuanNotLikeByRank(
			String code, String name, String mrank) {

		List<JianChaRenYuan> jianChaRenYuans = new ArrayList<JianChaRenYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM JIANGUANRENYUAN WHERE CODE =  ? AND NAME = ? AND RANK = ? ORDER BY CODE ASC ",
						new String[] { code, name, mrank });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			name = cursor.getString(cursor.getColumnIndex("NAME"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaRenYuans.add(new JianChaRenYuan(id, name, rank, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaRenYuans;
	}

	/**
	 * 查询出所有检查人员
	 */
	public List<JianChaRenYuan> queryAllJianChaRenYuan(String code) {

		List<JianChaRenYuan> jianChaRenYuans = new ArrayList<JianChaRenYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE  CODE = ? ORDER BY CODE ASC) UNION ALL SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE   CODE <> ? AND CODE||'' LIKE '"
								+ code + "%' ORDER BY CODE ASC)", new String[] {
								code, code });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String nameStr = cursor.getString(cursor.getColumnIndex("NAME"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaRenYuans.add(new JianChaRenYuan(id, nameStr, rank, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaRenYuans;
	}

	/**
	 * 查询出所有检查人员by rank 3
	 */
	public List<JianChaRenYuan> queryAllJianChaRenYuanByRank(String code,
															 String mrenk) {

		List<JianChaRenYuan> jianChaRenYuans = new ArrayList<JianChaRenYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,RANK,CODE  FROM  (SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE  CODE = ? AND RANK=? ORDER BY CODE ASC)"
								+ "  UNION ALL SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE   CODE <> ?"
								+
								// " AND CODE||'' LIKE '"
								// + code + "%' " +
								"ORDER BY CODE ASC))", new String[] { code,
								mrenk, code });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String nameStr = cursor.getString(cursor.getColumnIndex("NAME"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaRenYuans.add(new JianChaRenYuan(id, nameStr, rank, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaRenYuans;
	}

	/**
	 * 根据名称过滤检查人员
	 *
	 * @param filter
	 * @return
	 */
	public List<JianChaRenYuan> queryAllJianChaRenYuan(String code,
													   String filter, Integer rankParam) {

		List<JianChaRenYuan> jianChaRenYuans = new ArrayList<JianChaRenYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE  CODE = ? AND NAME LIKE ? ORDER BY CODE ASC) UNION ALL SELECT ID,NAME,RANK,CODE  FROM ( SELECT ID,NAME,RANK,CODE FROM JIANGUANRENYUAN WHERE  CODE <> ? AND CODE||'' LIKE '"
								+ code
								+ "%'    AND NAME LIKE ? ORDER BY CODE ASC)",
						new String[] { code, "%" + filter + "%", code,
								"%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			Integer rank = cursor.getInt(cursor.getColumnIndex("RANK"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			if (rankParam != null) {
				if (rank == rankParam) {
					jianChaRenYuans.add(new JianChaRenYuan(id, name, rank,
							codeVal));
				}
			} else {
				jianChaRenYuans
						.add(new JianChaRenYuan(id, name, rank, codeVal));
			}

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaRenYuans;
	}

	/**
	 * 查询所有检查行业
	 *
	 * @param filter
	 * @return
	 */
	public List<JianChaHangYe> queryAllJianChaHangYe() {

		List<JianChaHangYe> jianChaHangYes = new ArrayList<JianChaHangYe>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM JIANCHAHANGYE ", null);

		while (cursor.moveToNext()) {

			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			jianChaHangYes.add(new JianChaHangYe(id, name));

		}

		if (cursor != null) {
			cursor.close();
		}

		return jianChaHangYes;
	}

	/**
	 * 根据ID查询是否存在这个记录
	 */
	public int queryCountJianDuJianChaById(String id, String username) {

		int count = 0;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT COUNT(*) FROM JIANDUJIANCHA WHERE ID = ? AND USERNAME = ?",
						new String[] { id, username });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;
	}

	/**
	 * 根据ID查询是否存在这个产品检测记录
	 */
	public int queryCountChanPinJianCeById(String id, String username) {

		int count = 0;

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT COUNT(*) FROM CHANPINJIANCERECORD WHERE ID = ? AND USERNAME = ?",
						new String[] { id, username });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;
	}

	/**
	 * 根据ID检查单位的数量
	 */
	public int queryCountBeiJianDanWeiByTownId(String code,
											   JianGuanDuiXiangFilter filter) {

		int count = 0;

		SQLiteDatabase db = getReadableDatabase();

		String sql = "SELECT COUNT(*) FROM BEIJIANDANWEI  WHERE CODE LIKE  '"
				+ code + "%'";

		if (filter != null && filter.getIds().size() > 0) {

			// 如果没有Where 说明第一个code 没有添加
			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND ";
			}

			sql += "ID IN (";

			for (String id : filter.getIds()) {

				sql += "'" + id + "'";

				if (filter.getIds().indexOf(id) != filter.getIds().size() - 1) {

					sql += ",";
				} else {
					sql += ")";
				}

			}

		}

		// 如果没有Where 说明第一个code 没有添加
		if ((filter != null && filter.getKinds().size() > 0)) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "KIND IN ( ";

			for (int kind : filter.getKinds()) {

				sql += kind;

				if (filter.getKinds().indexOf(kind) != filter.getKinds().size() - 1) {

					sql += ",";
				} else {
					sql += ")  ";
				}
			}

		}

		if (filter != null && filter.getCategory().size() > 0) {

			if (sql.indexOf("WHERE") < 0) {
				sql += " WHERE ";

			} else {
				sql += " AND  ";
			}

			sql += "(";

			for (int category : filter.getCategory()) {
				sql += " CATEGORY LIKE '%" + category + "%'  ";

				if (filter.getCategory().indexOf(category) != filter
						.getCategory().size() - 1) {

					sql += "OR ";
				}
			}

			sql += ")";

		}

		Log.d(CommonConstants.LOG_TAG, sql);

		Cursor cursor = db.rawQuery(sql, new String[] {});

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;
	}

	// /**
	// * 插入监管记录
	// */
	// public void insertOrUpdateJianDuJianChaRecord(
	// JianDuJianChaRecord jianDuJianChaRecord, String username) {
	//
	// if (jianDuJianChaRecord != null) {
	//
	// SQLiteDatabase db = getReadableDatabase();
	//
	// int count = queryCountJianDuJianChaById(
	// jianDuJianChaRecord.getId(), username);
	//
	// // 所有的值
	// ContentValues values = new ContentValues();
	//
	// values.put("USERNAME", username);
	//
	// if (jianDuJianChaRecord.getTowns()[0] != null) {
	//
	// StringBuffer city = new StringBuffer();
	// city.append(jianDuJianChaRecord.getTowns()[0].getCode());
	//
	// city.append(",");
	//
	// city.append(jianDuJianChaRecord.getTowns()[0].getName());
	//
	// values.put("CITY", city.toString());
	// } else {
	// values.putNull("CITY");
	// }
	//
	// if (jianDuJianChaRecord.getTowns()[1] != null) {
	//
	// StringBuffer area = new StringBuffer();
	//
	// area.append(jianDuJianChaRecord.getTowns()[1].getCode());
	//
	// area.append(",");
	//
	// area.append(jianDuJianChaRecord.getTowns()[1].getName());
	//
	// values.put("AREA", area.toString());
	//
	// } else {
	//
	// values.putNull("AREA");
	// }
	//
	// if (jianDuJianChaRecord.getTowns()[2] != null) {
	//
	// StringBuffer town = new StringBuffer();
	// town.append(jianDuJianChaRecord.getTowns()[2].getCode());
	//
	// town.append(",");
	//
	// town.append(jianDuJianChaRecord.getTowns()[2].getName());
	//
	// values.put("TOWN", town.toString());
	// } else {
	// values.putNull("TOWN");
	// }
	//
	// // 被检单位
	// if (jianDuJianChaRecord.getBeiJianDanWei() != null) {
	//
	// StringBuffer beiJianDanWeis = new StringBuffer();
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .getId());
	//
	// beiJianDanWeis.append(",");
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .getName());
	//
	// beiJianDanWeis.append(",");
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .isCreateShouJianDanWei());
	//
	// beiJianDanWeis.append(",");
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .getAddress());
	//
	// beiJianDanWeis.append(",");
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .getCharge());
	//
	// beiJianDanWeis.append(",");
	//
	// beiJianDanWeis.append(jianDuJianChaRecord.getBeiJianDanWei()
	// .getMobile());
	//
	// values.put("BEIJIANDANWEI", beiJianDanWeis.toString());
	//
	// } else {
	// values.putNull("BEIJIANDANWEI");
	// }
	//
	// // 检查单位
	// if (jianDuJianChaRecord.getJianChaDanWeis() != null
	// && jianDuJianChaRecord.getJianChaDanWeis().size() > 0) {
	//
	// StringBuffer jianChaDanWeis = new StringBuffer();
	//
	// for (int i = 0; i < jianDuJianChaRecord.getJianChaDanWeis()
	// .size(); i++) {
	//
	// JianChaDanWei jianChaDanWei = jianDuJianChaRecord
	// .getJianChaDanWeis().get(i);
	//
	// if (jianChaDanWei.getId() != null) {
	// jianChaDanWeis.append(jianChaDanWei.getId());
	// jianChaDanWeis.append(",");
	// }
	//
	// jianChaDanWeis.append(jianChaDanWei.getName());
	//
	// jianChaDanWeis.append("#");
	//
	// }
	//
	// if (jianChaDanWeis.length() > 0) {
	// // 清除最后一个字符
	// jianChaDanWeis.deleteCharAt(jianChaDanWeis.length() - 1);
	// }
	//
	// values.put("JIANCHADANWEI", jianChaDanWeis.toString());
	//
	// } else {
	// values.putNull("JIANCHADANWEI");
	// }
	//
	// // 检查人员
	// if (jianDuJianChaRecord.getJianChaReYuans() != null
	// && jianDuJianChaRecord.getJianChaReYuans().size() > 0) {
	//
	// StringBuffer jianChaRenYuans = new StringBuffer();
	//
	// for (int i = 0; i < jianDuJianChaRecord.getJianChaReYuans()
	// .size(); i++) {
	//
	// JianChaRenYuan jianChaRenYuan = jianDuJianChaRecord
	// .getJianChaReYuans().get(i);
	//
	// if (jianChaRenYuan.getId() != null) {
	//
	// jianChaRenYuans.append(jianChaRenYuan.getId());
	// jianChaRenYuans.append(",");
	// }
	//
	// jianChaRenYuans.append(jianChaRenYuan.getName());
	//
	// jianChaRenYuans.append("#");
	//
	// }
	//
	// if (jianChaRenYuans.length() > 0) {
	// // 清除最后一个字符
	// jianChaRenYuans.deleteCharAt(jianChaRenYuans.length() - 1);
	// }
	//
	// values.put("JIANCHARENYUAN", jianChaRenYuans.toString());
	//
	// } else {
	// values.putNull("JIANCHARENYUAN");
	// }
	//
	// // 检查行业
	// if (jianDuJianChaRecord.getJianChaHangYes() != null
	// && jianDuJianChaRecord.getJianChaHangYes().size() > 0) {
	//
	// StringBuffer jianChaHangYes = new StringBuffer();
	//
	// for (int i = 0; i < jianDuJianChaRecord.getJianChaHangYes()
	// .size(); i++) {
	//
	// JianChaHangYe jianChaHangYe = jianDuJianChaRecord
	// .getJianChaHangYes().get(i);
	//
	// jianChaHangYes.append(jianChaHangYe.getId());
	// jianChaHangYes.append(",");
	// jianChaHangYes.append(jianChaHangYe.getName());
	// jianChaHangYes.append("#");
	//
	// }
	//
	// if (jianChaHangYes.length() > 0) {
	// // 清除最后一个字符
	// jianChaHangYes.deleteCharAt(jianChaHangYes.length() - 1);
	// }
	//
	// values.put("JIANCHAHANGYE", jianChaHangYes.toString());
	//
	// } else {
	// values.putNull("JIANCHAHANGYE");
	// }
	//
	// // 检查内容
	// if (jianDuJianChaRecord.getJianChaNeiRongs() != null
	// && jianDuJianChaRecord.getJianChaNeiRongs().size() > 0) {
	//
	// StringBuffer jianChaNeiRongs = new StringBuffer();
	//
	// for (int i = 0; i < jianDuJianChaRecord.getJianChaNeiRongs()
	// .size(); i++) {
	//
	// JianChaNeiRong jianChaNeiRong = jianDuJianChaRecord
	// .getJianChaNeiRongs().get(i);
	//
	// jianChaNeiRongs.append(jianChaNeiRong.getId());
	// jianChaNeiRongs.append(",");
	// jianChaNeiRongs.append(jianChaNeiRong.getName());
	// jianChaNeiRongs.append("#");
	//
	// }
	//
	// if (jianChaNeiRongs.length() > 0) {
	// // 清除最后一个字符
	// jianChaNeiRongs.deleteCharAt(jianChaNeiRongs.length() - 1);
	// }
	//
	// values.put("JIANCHANEIRONG", jianChaNeiRongs.toString());
	//
	// } else {
	// values.putNull("JIANCHANEIRONG");
	// }
	//
	// // 产地环境的安全性
	// if (jianDuJianChaRecord.getJianChaJieGuos() != null
	// && jianDuJianChaRecord.getJianChaJieGuos()[0] != null) {
	//
	// StringBuffer chanDiHuanJingAnQuanXing = new StringBuffer();
	//
	// chanDiHuanJingAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[0].getId());
	//
	// chanDiHuanJingAnQuanXing.append(",");
	//
	// chanDiHuanJingAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[0].getName());
	//
	// if (jianDuJianChaRecord.getJianChaJieGuos()[0].getProblem() != null
	// && !"".equals(jianDuJianChaRecord.getJianChaJieGuos()[0]
	// .getProblem())) {
	//
	// chanDiHuanJingAnQuanXing.append(",");
	// chanDiHuanJingAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[0].getProblem());
	//
	// }
	//
	// values.put("CHANDIANQUANXING",
	// chanDiHuanJingAnQuanXing.toString());
	//
	// } else {
	// values.putNull("CHANDIANQUANXING");
	// }
	//
	// // 生产经营的规范性
	// if (jianDuJianChaRecord.getJianChaJieGuos() != null
	// && jianDuJianChaRecord.getJianChaJieGuos()[1] != null) {
	//
	// StringBuffer jingYingGuiFanXing = new StringBuffer();
	//
	// jingYingGuiFanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[1].getId());
	//
	// jingYingGuiFanXing.append(",");
	//
	// jingYingGuiFanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[1].getName());
	//
	// if (jianDuJianChaRecord.getJianChaJieGuos()[1].getProblem() != null
	// && !"".equals(jianDuJianChaRecord.getJianChaJieGuos()[1]
	// .getProblem())) {
	//
	// jingYingGuiFanXing.append(",");
	// jingYingGuiFanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[1].getProblem());
	//
	// }
	//
	// values.put("JINGYINGGUIFANXING", jingYingGuiFanXing.toString());
	//
	// } else {
	// values.putNull("JINGYINGGUIFANXING");
	// }
	//
	// // 生产质量安全性
	// if (jianDuJianChaRecord.getJianChaJieGuos() != null
	// && jianDuJianChaRecord.getJianChaJieGuos()[2] != null) {
	//
	// StringBuffer zhiLiangAnQuanXing = new StringBuffer();
	//
	// zhiLiangAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[2].getId());
	//
	// zhiLiangAnQuanXing.append(",");
	//
	// zhiLiangAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[2].getName());
	//
	// if (jianDuJianChaRecord.getJianChaJieGuos()[2].getProblem() != null
	// && !"".equals(jianDuJianChaRecord.getJianChaJieGuos()[2]
	// .getProblem())) {
	//
	// zhiLiangAnQuanXing.append(",");
	// zhiLiangAnQuanXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[2].getProblem());
	//
	// }
	//
	// values.put("ZHILIANGANQUANXING", zhiLiangAnQuanXing.toString());
	//
	// } else {
	// values.putNull("ZHILIANGANQUANXING");
	// }
	//
	// // 包装标识的合法性
	// if (jianDuJianChaRecord.getJianChaJieGuos() != null
	// && jianDuJianChaRecord.getJianChaJieGuos()[3] != null) {
	//
	// StringBuffer biaoZhiHeFaXing = new StringBuffer();
	//
	// biaoZhiHeFaXing
	// .append(jianDuJianChaRecord.getJianChaJieGuos()[3]
	// .getId());
	//
	// biaoZhiHeFaXing.append(",");
	//
	// biaoZhiHeFaXing
	// .append(jianDuJianChaRecord.getJianChaJieGuos()[3]
	// .getName());
	//
	// if (jianDuJianChaRecord.getJianChaJieGuos()[3].getProblem() != null
	// && !"".equals(jianDuJianChaRecord.getJianChaJieGuos()[3]
	// .getProblem())) {
	//
	// biaoZhiHeFaXing.append(",");
	//
	// biaoZhiHeFaXing.append(jianDuJianChaRecord
	// .getJianChaJieGuos()[3].getProblem());
	//
	// }
	//
	// values.put("BIAOZHIHEFAXING", biaoZhiHeFaXing.toString());
	//
	// } else {
	// values.putNull("BIAOZHIHEFAXING");
	// }
	//
	// // 其他
	// if (jianDuJianChaRecord.getJianChaJieGuos() != null
	// && jianDuJianChaRecord.getJianChaJieGuos()[4] != null) {
	//
	// StringBuffer qita = new StringBuffer();
	//
	// qita.append(jianDuJianChaRecord.getJianChaJieGuos()[4].getId());
	//
	// qita.append(",");
	//
	// qita.append(jianDuJianChaRecord.getJianChaJieGuos()[4]
	// .getName());
	//
	// if (jianDuJianChaRecord.getJianChaJieGuos()[4].getProblem() != null
	// && !"".equals(jianDuJianChaRecord.getJianChaJieGuos()[4]
	// .getProblem())) {
	//
	// qita.append(",");
	// qita.append(jianDuJianChaRecord.getJianChaJieGuos()[4]
	// .getProblem());
	//
	// }
	//
	// values.put("QITA", qita.toString());
	//
	// } else {
	// values.putNull("QITA");
	// }
	//
	// // 日常监管
	// if (jianDuJianChaRecord.getRiChangJianGuan() != null) {
	//
	// StringBuffer riChangJianGuan = new StringBuffer();
	//
	// riChangJianGuan.append(jianDuJianChaRecord.getRiChangJianGuan()
	// .getId());
	//
	// riChangJianGuan.append(",");
	//
	// riChangJianGuan.append(jianDuJianChaRecord.getRiChangJianGuan()
	// .getName());
	//
	// riChangJianGuan.append(",");
	//
	// riChangJianGuan.append(jianDuJianChaRecord.getRiChangJianGuan()
	// .getProblem());
	//
	// values.put("RICHANGJIANGUAN", riChangJianGuan.toString());
	//
	// } else {
	// values.putNull("RICHANGJIANGUAN");
	// }
	//
	// // 整改意见
	// if (jianDuJianChaRecord.getZhengGaiYiJian() != null
	// && !"".equals(jianDuJianChaRecord.getZhengGaiYiJian())) {
	// values.put("ZHENGGAIYIJIAN",
	// jianDuJianChaRecord.getZhengGaiYiJian());
	// } else {
	// values.putNull("ZHENGGAIYIJIAN");
	// }
	//
	// // 签名
	// if (jianDuJianChaRecord.getQianMingPath() != null
	// && !"".equals(jianDuJianChaRecord.getQianMingPath())) {
	// values.put("QIANMING", jianDuJianChaRecord.getQianMingPath());
	// } else {
	// values.putNull("QIANMING");
	// }
	//
	// values.put("STATE", jianDuJianChaRecord.getState());
	//
	// // 清空照片
	// deletePhotoByRecordId(jianDuJianChaRecord.getId());
	//
	// // 时间
	// values.put("TIME", jianDuJianChaRecord.getTime());
	//
	// if (count > 0) {
	//
	// // 存在这条记录,则更新
	// db.update("JIANDUJIANCHA", values, "ID = ?",
	// new String[] { jianDuJianChaRecord.getId() });
	//
	// } else {
	//
	// values.put("ID", jianDuJianChaRecord.getId());
	//
	// db.insert("JIANDUJIANCHA", null, values);
	// }
	//
	// // 插入所有的照片
	// insertPhotos(jianDuJianChaRecord.getPhotos(),
	// jianDuJianChaRecord.getId());
	// }
	//
	// }

	/**
	 * 清理照片
	 */
	public void deletePhotoByRecordId(String recordId) {

		SQLiteDatabase db = getReadableDatabase();

		db.delete("PHOTOS", "RECORD_ID = ?", new String[] { recordId });

	}

	public void delete(String tableName) {
		SQLiteDatabase db = getReadableDatabase();

		db.delete(tableName, null, null);
	}

	/**
	 * 清理产品检测的照片信息
	 *
	 * @param recordId
	 */
	public void deletePhotoByRecordIdFromChanPinJianCe(String recordId) {

		SQLiteDatabase db = getReadableDatabase();

		db.delete("CHANPINJIANCE_PHOTOS", "CHANPINJIANCE_ID = ?",
				new String[] { recordId });

	}

	/**
	 * 插入图片
	 */
	public void insertPhotos(List<Photo> photos, String recordId) {

		SQLiteDatabase db = getReadableDatabase();

		ContentValues values = new ContentValues();

		if (photos != null && photos.size() > 0) {

			db.beginTransaction();

			for (Photo photo : photos) {

				values.clear();

				values.putNull("ID");
				values.put("RECORD_ID", recordId);

				if (photo.getPhotoTime() != null) {

					values.put("PHOTOTIME", photo.getPhotoTime());

				}

				if (photo.getLatitude() != null) {

					values.put("LATITUDE", photo.getLatitude());
				}

				if (photo.getLongitude() != null) {

					values.put("LONGITUDE", photo.getLongitude());
				}

				if (photo.getComment() != null) {

					values.put("COMMENT", photo.getComment());
				}

				// 如果是上传
				if (photo.isUpload()) {
					values.put("IS_UPLOAD", 1);
				} else {
					values.put("IS_UPLOAD", 0);
				}

				if (photo.getAddressDesc() != null) {

					values.put("ADDRESSDESC", photo.getAddressDesc());
				}

				if (photo.getBigPhotoPath() != null) {

					values.put("BIGPHOTOPATH", photo.getBigPhotoPath());
				}

				if (photo.getSmallPhotoPath() != null
						&& photo.getSmallPhotoPath() instanceof String) {

					values.put("SMALLPHOTOPATH",
							(String) photo.getSmallPhotoPath());
				}

				db.insert("PHOTOS", null, values);

			}
			db.setTransactionSuccessful();

			db.endTransaction();

		}

	}

	/**
	 * 插入图片,产品检测的图片
	 */
	public void insertPhotosFromChanPinJianCe(List<Photo> photos,
											  String recordId) {

		SQLiteDatabase db = getReadableDatabase();

		ContentValues values = new ContentValues();

		if (photos != null && photos.size() > 0) {

			db.beginTransaction();

			for (Photo photo : photos) {

				values.clear();

				values.putNull("ID");
				values.put("CHANPINJIANCE_ID", recordId);

				if (photo.getPhotoTime() != null) {

					values.put("PHOTOTIME", photo.getPhotoTime());

				}

				if (photo.getLatitude() != null) {

					values.put("LATITUDE", photo.getLatitude());
				}

				if (photo.getLongitude() != null) {

					values.put("LONGITUDE", photo.getLongitude());
				}

				if (photo.getComment() != null) {

					values.put("COMMENT", photo.getComment());
				}

				// 如果是上传
				if (photo.isUpload()) {
					values.put("IS_UPLOAD", 1);
				} else {
					values.put("IS_UPLOAD", 0);
				}

				if (photo.getAddressDesc() != null) {

					values.put("ADDRESSDESC", photo.getAddressDesc());
				}

				if (photo.getBigPhotoPath() != null) {

					values.put("BIGPHOTOPATH", photo.getBigPhotoPath());
				}

				if (photo.getSmallPhotoPath() != null
						&& photo.getSmallPhotoPath() instanceof String) {

					values.put("SMALLPHOTOPATH",
							(String) photo.getSmallPhotoPath());
				}

				db.insert("CHANPINJIANCE_PHOTOS", null, values);

			}
			db.setTransactionSuccessful();

			db.endTransaction();

		}

	}

	/**
	 * 查询存在的图片
	 */
	public List<Photo> queryPhotoByRecordId(SQLiteDatabase db, String recordId) {

		List<Photo> photos = new ArrayList<Photo>();

		if (recordId != null) {

			Cursor cursor = db.rawQuery(
					"SELECT * FROM PHOTOS WHERE RECORD_ID = ?",
					new String[] { recordId });

			while (cursor.moveToNext()) {

				Photo photo = new Photo();

				int id = cursor.getInt(cursor.getColumnIndex("ID"));

				String photoTime = cursor.getString(cursor
						.getColumnIndex("PHOTOTIME"));

				Double latitude = cursor.getDouble(cursor
						.getColumnIndex("LATITUDE"));

				Double longitude = cursor.getDouble(cursor
						.getColumnIndex("LONGITUDE"));

				String comment = cursor.getString(cursor
						.getColumnIndex("COMMENT"));

				String addressDesc = cursor.getString(cursor
						.getColumnIndex("ADDRESSDESC"));

				String bigPhotoPath = cursor.getString(cursor
						.getColumnIndex("BIGPHOTOPATH"));

				String smallPhotoPath = cursor.getString(cursor
						.getColumnIndex("SMALLPHOTOPATH"));

				Integer isUpload = cursor.getInt(cursor
						.getColumnIndex("IS_UPLOAD"));

				photo.setId(id);

				photo.setPhotoTime(photoTime);

				photo.setLatitude(latitude);

				photo.setLongitude(longitude);

				photo.setComment(comment);

				if (isUpload == 1) {
					photo.setUpload(true);
				} else {
					photo.setUpload(false);
				}

				photo.setAddressDesc(addressDesc);

				photo.setBigPhotoPath(bigPhotoPath);

				photo.setSmallPhotoPath(smallPhotoPath);

				photos.add(photo);

			}

			if (cursor != null) {
				cursor.close();
			}
		}

		return photos;
	}

	/**
	 * 查询存在的图片
	 */
	public List<Photo> queryPhotoByRecordIdFromChanPinJianCe(SQLiteDatabase db,
															 String recordId) {

		List<Photo> photos = new ArrayList<Photo>();

		if (recordId != null) {

			Cursor cursor = db
					.rawQuery(
							"SELECT * FROM CHANPINJIANCE_PHOTOS WHERE  CHANPINJIANCE_ID = ?",
							new String[] { recordId });

			while (cursor.moveToNext()) {

				Photo photo = new Photo();

				int id = cursor.getInt(cursor.getColumnIndex("ID"));

				String photoTime = cursor.getString(cursor
						.getColumnIndex("PHOTOTIME"));

				Double latitude = cursor.getDouble(cursor
						.getColumnIndex("LATITUDE"));

				Double longitude = cursor.getDouble(cursor
						.getColumnIndex("LONGITUDE"));

				String comment = cursor.getString(cursor
						.getColumnIndex("COMMENT"));

				String addressDesc = cursor.getString(cursor
						.getColumnIndex("ADDRESSDESC"));

				String bigPhotoPath = cursor.getString(cursor
						.getColumnIndex("BIGPHOTOPATH"));

				String smallPhotoPath = cursor.getString(cursor
						.getColumnIndex("SMALLPHOTOPATH"));

				Integer isUpload = cursor.getInt(cursor
						.getColumnIndex("IS_UPLOAD"));

				photo.setId(id);

				photo.setPhotoTime(photoTime);

				photo.setLatitude(latitude);

				photo.setLongitude(longitude);

				photo.setComment(comment);

				if (isUpload == 1) {
					photo.setUpload(true);
				} else {
					photo.setUpload(false);
				}

				photo.setAddressDesc(addressDesc);

				photo.setBigPhotoPath(bigPhotoPath);

				photo.setSmallPhotoPath(smallPhotoPath);

				photos.add(photo);

			}

			if (cursor != null) {
				cursor.close();
			}
		}

		return photos;
	}

	/**
	 * 查询出存在记录的数目
	 *
	 * @param state
	 * @return
	 */
	public int queryJianDuJianChaRecordCount(int state, String username) {

		int count = 0;

		String sql = "SELECT COUNT(*) FROM JIANDUJIANCHA WHERE STATE = ? AND USERNAME = ? ORDER BY TIME DESC ";

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(sql, new String[] { state + "", username });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;

	}

	/**
	 * 查询出产品检测记录的数目
	 *
	 * @param state
	 * @return
	 */
	public int queryChanPinJianCeRecordCount(int state, String username) {

		int count = 0;

		String sql = "SELECT COUNT(*) FROM CHANPINJIANCERECORD WHERE STATE = ? AND USERNAME = ? ";

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(sql, new String[] { state + "", username });

		if (cursor.moveToNext()) {
			count = cursor.getInt(0);
		}

		if (cursor != null) {
			cursor.close();
		}

		return count;

	}

	/**
	 * 查询监督检查
	 *
	 * @return
	 */
	public List<JianDuJianChaRecord> queryJianDuJianChaRecordByState(
			SQLiteDatabase db, int state, String username) {

		List<JianDuJianChaRecord> records = new ArrayList<JianDuJianChaRecord>();

		// 查询出状态为缓存的
		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM JIANDUJIANCHA WHERE STATE = ? AND USERNAME = ? ORDER BY TIME DESC ",
						new String[] { String.valueOf(state), username });

		while (cursor.moveToNext()) {

			JianDuJianChaRecord jianDuJianChaRecord = new JianDuJianChaRecord();

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			// 设置ID
			jianDuJianChaRecord.setId(id);

			String cityInfo = cursor.getString(cursor.getColumnIndex("CITY"));

			if (CharsetUtil.isNotNull(cityInfo)) {

				String[] cityInfoArr = cityInfo.split(",");

				if (cityInfoArr.length == 2) {

					Town city = new Town(cityInfoArr[0], null, null,
							cityInfoArr[1]);

					jianDuJianChaRecord.getTowns()[0] = city;
				}

			}

			String areaInfo = cursor.getString(cursor.getColumnIndex("AREA"));

			if (CharsetUtil.isNotNull(areaInfo)) {

				String[] areaInfos = areaInfo.split(",");

				if (areaInfos.length == 2) {

					Town area = new Town(areaInfos[0], null, null, areaInfos[1]);

					jianDuJianChaRecord.getTowns()[1] = area;
				}

			}

			String townInfo = cursor.getString(cursor.getColumnIndex("TOWN"));

			if (CharsetUtil.isNotNull(townInfo)) {

				String[] townInfos = townInfo.split(",");

				if (townInfos.length == 2) {

					Town town = new Town(townInfos[0], null, null, townInfos[1]);

					jianDuJianChaRecord.getTowns()[2] = town;
				}

			}

			String beiJianDanWeiInfo = cursor.getString(cursor
					.getColumnIndex("BEIJIANDANWEI"));

			if (CharsetUtil.isNotNull(beiJianDanWeiInfo)) {

				String[] beiJianDanWeiInfoArr = beiJianDanWeiInfo.split(",");

				BeiJianDanWei beiJianDanWei = new BeiJianDanWei(
						beiJianDanWeiInfoArr[0], beiJianDanWeiInfoArr[1]);

				jianDuJianChaRecord.setBeiJianDanWei(beiJianDanWei);

				boolean bool = Boolean.parseBoolean(beiJianDanWeiInfoArr[2]);

				beiJianDanWei.setCreateShouJianDanWei(bool);

				String address = null;
				String charge = null;

				String mobile = null;

				try {

					address = beiJianDanWeiInfoArr[3];
					charge = beiJianDanWeiInfoArr[4];
					mobile = beiJianDanWeiInfoArr[5];

				} catch (ArrayIndexOutOfBoundsException e) {

				}

				beiJianDanWei.setAddress(address);

				beiJianDanWei.setCharge(charge);

				beiJianDanWei.setMobile(mobile);

			}

			String jianChaDanWeiInfo = cursor.getString(cursor
					.getColumnIndex("JIANCHADANWEI"));

			if (CharsetUtil.isNotNull(jianChaDanWeiInfo)) {
				String[] jianChaDanWeiInfos = jianChaDanWeiInfo.split("#");

				for (String jianChaDanWeiInf : jianChaDanWeiInfos) {

					String[] jianChaDanWeiInfoArr = jianChaDanWeiInf.split(",");

					if (jianChaDanWeiInfoArr.length == 1) {

						JianChaDanWei jianChaDanWei = new JianChaDanWei(null,
								jianChaDanWeiInfoArr[0]);
						jianDuJianChaRecord.getJianChaDanWeis().add(
								jianChaDanWei);

					}

					if (jianChaDanWeiInfoArr.length == 2) {

						JianChaDanWei jianChaDanWei = new JianChaDanWei(
								jianChaDanWeiInfoArr[0],
								jianChaDanWeiInfoArr[1]);

						jianDuJianChaRecord.getJianChaDanWeis().add(
								jianChaDanWei);

					}

				}
			}

			String jianChaRenYuanInfo = cursor.getString(cursor
					.getColumnIndex("JIANCHARENYUAN"));

			if (CharsetUtil.isNotNull(jianChaRenYuanInfo)) {
				String[] jianChaRenYuanInfos = jianChaRenYuanInfo.split("#");

				for (String jianChaRenYuanInf : jianChaRenYuanInfos) {

					String[] jianChaRenYuanInfoArr = jianChaRenYuanInf
							.split(",");

					if (jianChaRenYuanInfoArr.length == 1) {

						JianChaRenYuan jianChaRenYuan = new JianChaRenYuan(
								null, jianChaRenYuanInfoArr[0], null);

						jianDuJianChaRecord.getJianChaReYuans().add(
								jianChaRenYuan);

					}

					if (jianChaRenYuanInfoArr.length == 2) {

						JianChaRenYuan jianChaRenYuan = new JianChaRenYuan(
								jianChaRenYuanInfoArr[0],
								jianChaRenYuanInfoArr[1], null);

						jianDuJianChaRecord.getJianChaReYuans().add(
								jianChaRenYuan);

					}

				}
			}

			String jianChaHangYeInfo = cursor.getString(cursor
					.getColumnIndex("JIANCHAHANGYE"));

			if (CharsetUtil.isNotNull(jianChaHangYeInfo)) {
				String[] jianChaHangYeInfos = jianChaHangYeInfo.split("#");

				for (String jianChaHangYeInf : jianChaHangYeInfos) {

					String[] jianChaHangYeInfoArr = jianChaHangYeInf.split(",");

					if (jianChaHangYeInfoArr.length == 2) {

						JianChaHangYe jianChaHangYe = new JianChaHangYe(
								Integer.parseInt(jianChaHangYeInfoArr[0]),
								jianChaHangYeInfoArr[1]);

						jianDuJianChaRecord.getJianChaHangYes().add(
								jianChaHangYe);

					}

				}
			}

			String jianChaNeiRongInfo = cursor.getString(cursor
					.getColumnIndex("JIANCHANEIRONG"));

			if (CharsetUtil.isNotNull(jianChaNeiRongInfo)) {
				String[] jianChaNeiRongInfos = jianChaNeiRongInfo.split("#");

				for (String jianChaNeiRongInf : jianChaNeiRongInfos) {

					String[] jianChaNeiRongInfoArr = jianChaNeiRongInf
							.split(",");

					if (jianChaNeiRongInfoArr.length == 2) {

						JianChaNeiRong jianChaNeiRong = new JianChaNeiRong(
								Integer.parseInt(jianChaNeiRongInfoArr[0]),
								jianChaNeiRongInfoArr[1]);

						jianDuJianChaRecord.getJianChaNeiRongs().add(
								jianChaNeiRong);

					}

				}
			}

			String chanDiAnQuanXingInfo = cursor.getString(cursor
					.getColumnIndex("CHANDIANQUANXING"));

			if (CharsetUtil.isNotNull(chanDiAnQuanXingInfo)) {

				String[] chanDiAnQuanXingInfos = chanDiAnQuanXingInfo
						.split(",");

				if (chanDiAnQuanXingInfos.length == 2) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(chanDiAnQuanXingInfos[0]),
							chanDiAnQuanXingInfos[1]);

					jianDuJianChaRecord.getJianChaJieGuos()[0] = jianChaJieGuo;

				} else if (chanDiAnQuanXingInfos.length == 3) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(chanDiAnQuanXingInfos[0]),
							chanDiAnQuanXingInfos[1], chanDiAnQuanXingInfos[2]);

					jianDuJianChaRecord.getJianChaJieGuos()[0] = jianChaJieGuo;
				}

			}

			String jingYingGuiFanXingInfo = cursor.getString(cursor
					.getColumnIndex("JINGYINGGUIFANXING"));

			if (CharsetUtil.isNotNull(jingYingGuiFanXingInfo)) {

				String[] jingYingGuiFanXingInfos = jingYingGuiFanXingInfo
						.split(",");

				if (jingYingGuiFanXingInfos.length == 2) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(jingYingGuiFanXingInfos[0]),
							jingYingGuiFanXingInfos[1]);

					jianDuJianChaRecord.getJianChaJieGuos()[1] = jianChaJieGuo;

				} else if (jingYingGuiFanXingInfos.length == 3) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(jingYingGuiFanXingInfos[0]),
							jingYingGuiFanXingInfos[1],
							jingYingGuiFanXingInfos[2]);

					jianDuJianChaRecord.getJianChaJieGuos()[1] = jianChaJieGuo;
				}

			}

			String zhiLiangAnQuanXingInfo = cursor.getString(cursor
					.getColumnIndex("ZHILIANGANQUANXING"));

			if (CharsetUtil.isNotNull(zhiLiangAnQuanXingInfo)) {

				String[] zhiLiangAnQuanXingInfos = zhiLiangAnQuanXingInfo
						.split(",");

				if (zhiLiangAnQuanXingInfos.length == 2) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(zhiLiangAnQuanXingInfos[0]),
							zhiLiangAnQuanXingInfos[1]);

					jianDuJianChaRecord.getJianChaJieGuos()[2] = jianChaJieGuo;

				} else if (zhiLiangAnQuanXingInfos.length == 3) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(zhiLiangAnQuanXingInfos[0]),
							zhiLiangAnQuanXingInfos[1],
							zhiLiangAnQuanXingInfos[2]);

					jianDuJianChaRecord.getJianChaJieGuos()[2] = jianChaJieGuo;
				}

			}

			String biaoZhiHeFaXingInfo = cursor.getString(cursor
					.getColumnIndex("BIAOZHIHEFAXING"));

			if (CharsetUtil.isNotNull(biaoZhiHeFaXingInfo)) {

				String[] biaoZhiHeFaXingInfos = biaoZhiHeFaXingInfo.split(",");

				if (biaoZhiHeFaXingInfos.length == 2) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(biaoZhiHeFaXingInfos[0]),
							biaoZhiHeFaXingInfos[1]);

					jianDuJianChaRecord.getJianChaJieGuos()[3] = jianChaJieGuo;

				} else if (biaoZhiHeFaXingInfos.length == 3) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(biaoZhiHeFaXingInfos[0]),
							biaoZhiHeFaXingInfos[1], biaoZhiHeFaXingInfos[2]);

					jianDuJianChaRecord.getJianChaJieGuos()[3] = jianChaJieGuo;
				}

			}

			String qiTaInfo = cursor.getString(cursor.getColumnIndex("QITA"));

			if (CharsetUtil.isNotNull(qiTaInfo)) {

				String[] qiTaInfos = qiTaInfo.split(",");

				if (qiTaInfos.length == 2) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(qiTaInfos[0]), qiTaInfos[1]);

					jianDuJianChaRecord.getJianChaJieGuos()[4] = jianChaJieGuo;

				} else if (qiTaInfos.length == 3) {

					JianChaJieGuo jianChaJieGuo = new JianChaJieGuo(
							Integer.parseInt(qiTaInfos[0]), qiTaInfos[1],
							qiTaInfos[2]);

					jianDuJianChaRecord.getJianChaJieGuos()[4] = jianChaJieGuo;
				}

			}

			String qiChangJianGuanInfo = cursor.getString(cursor
					.getColumnIndex("RICHANGJIANGUAN"));

			if (CharsetUtil.isNotNull(qiChangJianGuanInfo)) {

				String[] riChangJianGuanInfos = qiChangJianGuanInfo.split(",");

				if (riChangJianGuanInfos.length == 2) {

					JianChaJieGuo riChangJianGuan = new JianChaJieGuo(
							Integer.parseInt(riChangJianGuanInfos[0]),
							riChangJianGuanInfos[1]);

					jianDuJianChaRecord.setRiChangJianGuan(riChangJianGuan);
				}

				if (riChangJianGuanInfos.length == 3) {
					JianChaJieGuo riChangJianGuan = new JianChaJieGuo(
							Integer.parseInt(riChangJianGuanInfos[0]),
							riChangJianGuanInfos[1], riChangJianGuanInfos[2]);
					jianDuJianChaRecord.setRiChangJianGuan(riChangJianGuan);
				}

			}

			String zhengGaiYiJian = cursor.getString(cursor
					.getColumnIndex("ZHENGGAIYIJIAN"));

			if (CharsetUtil.isNotNull(zhengGaiYiJian)) {
				jianDuJianChaRecord.setZhengGaiYiJian(zhengGaiYiJian);
			}

			String qianMing = cursor.getString(cursor
					.getColumnIndex("QIANMING"));

			if (CharsetUtil.isNotNull(qianMing)) {
				jianDuJianChaRecord.setQianMingPath(qianMing);
			}

			String time = cursor.getString(cursor.getColumnIndex("TIME"));

			jianDuJianChaRecord.setTime(time);

			// 查询已经存在的图片
			jianDuJianChaRecord.setPhotos(queryPhotoByRecordId(db,
					jianDuJianChaRecord.getId()));

			records.add(jianDuJianChaRecord);
		}

		if (cursor != null) {
			cursor.close();
		}

		return records;
	}

	/**
	 * 删除已经存在的记录
	 *
	 * @param id
	 */
	// public void deleteJianDuJianChaRecord(String id) {
	//
	// SQLiteDatabase db = getWritableDatabase();
	//
	// if (db.delete("JIANDUJIANCHA", "ID = ? ", new String[] { id }) > 0) {
	//
	// // 清理照片
	// deletePhotoByRecordId(id);
	// }
	//
	// }

	/**
	 * 删除已经存在的记录
	 *
	 * @param id
	 */
	// public void deleteChanPinJianCeRecord(String id) {
	//
	// SQLiteDatabase db = getWritableDatabase();
	//
	// db.beginTransaction();
	//
	// if (db.delete("CHANPINJIANCERECORD", "ID = ? ", new String[] { id }) > 0)
	// {
	//
	// deletePhotoByRecordIdFromChanPinJianCe(id);
	//
	// deleteYangPinByChanPinJianCeId(id);
	// }
	//
	// db.setTransactionSuccessful();
	//
	// db.endTransaction();
	//
	// }

	/**
	 * 插入一个联系人
	 *
	 * @param linkMain
	 */
	public void insertLinkMan(LinkMan linkMain) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		contentValues.put("ID", linkMain.getId());
		contentValues.put("REALNAME", linkMain.getRealName());
		contentValues.put("SEX", linkMain.getSex());

		if (CharsetUtil.isNotNull(linkMain.getTel())) {
			contentValues.put("TEL", linkMain.getTel());
		} else {
			contentValues.putNull("TEL");
		}

		if (CharsetUtil.isNotNull(linkMain.getMobile())) {
			contentValues.put("MOBILE", linkMain.getMobile());
		} else {
			contentValues.putNull("MOBILE");
		}

		if (CharsetUtil.isNotNull(linkMain.getDepartmentName())) {
			contentValues.put("DEPARTMENT_NAME", linkMain.getDepartmentName());
		} else {
			contentValues.putNull("DEPARTMENT_NAME");
		}

		if (CharsetUtil.isNotNull(linkMain.getPost())) {
			contentValues.put("POST", linkMain.getPost());
		} else {
			contentValues.putNull("POST");
		}

		contentValues.put("RANK", linkMain.getRank());

		if (linkMain.getLongitude() != null) {
			contentValues.put("LONGITUDE", linkMain.getLongitude());
		} else {
			contentValues.putNull("LONGITUDE");
		}

		if (linkMain.getLatitude() != null) {
			contentValues.put("LATITUDE", linkMain.getLatitude());
		} else {
			contentValues.putNull("LATITUDE");
		}

		contentValues.put("REGION_CODE", linkMain.getRegionCode());

		db.insert("LINKMAN", null, contentValues);

	}

	public void insertLinkMan(List<LinkMan> linkMans) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (LinkMan linkMain : linkMans) {

			contentValues.clear();

			contentValues.put("ID", linkMain.getId());
			contentValues.put("REALNAME", linkMain.getRealName());
			contentValues.put("SEX", linkMain.getSex());

			if (CharsetUtil.isNotNull(linkMain.getTel())) {
				contentValues.put("TEL", linkMain.getTel());
			} else {
				contentValues.putNull("TEL");
			}

			if (CharsetUtil.isNotNull(linkMain.getMobile())) {
				contentValues.put("MOBILE", linkMain.getMobile());
			} else {
				contentValues.putNull("MOBILE");
			}

			if (CharsetUtil.isNotNull(linkMain.getDepartmentName())) {
				contentValues.put("DEPARTMENT_NAME",
						linkMain.getDepartmentName());
			} else {
				contentValues.putNull("DEPARTMENT_NAME");
			}

			if (CharsetUtil.isNotNull(linkMain.getPost())) {
				contentValues.put("POST", linkMain.getPost());
			} else {
				contentValues.putNull("POST");
			}

			contentValues.put("RANK", linkMain.getRank());

			if (linkMain.getLongitude() != null) {
				contentValues.put("LONGITUDE", linkMain.getLongitude());
			} else {
				contentValues.putNull("LONGITUDE");
			}

			if (linkMain.getLatitude() != null) {
				contentValues.put("LATITUDE", linkMain.getLatitude());
			} else {
				contentValues.putNull("LATITUDE");
			}

			contentValues.put("REGION_CODE", linkMain.getRegionCode());

			// contentValues.put("ADDTIME", linkMain.getAddTime());
			// contentValues.put("MODIFYTIME", linkMain.getModifyTime());
			// contentValues.put("DELETETIME", linkMain.getDeleteTime());

			if (CharsetUtil.isNotNull(linkMain.getAddTime())) {
				contentValues.put("ADDTIME", linkMain.getAddTime());
			}

			if (CharsetUtil.isNotNull(linkMain.getModifyTime())) {
				contentValues.put("MODIFYTIME", linkMain.getModifyTime());
			}

			if (CharsetUtil.isNotNull(linkMain.getDeleteTime())) {
				contentValues.put("DELETETIME", linkMain.getDeleteTime());
			}

			db.insert("LINKMAN", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 增加或者修改
	 *
	 * @param linkMans
	 */
	public void insertOrUpdateLinkMan(List<LinkMan> linkMans) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		for (LinkMan linkMain : linkMans) {

			String sql = "SELECT COUNT(*) FROM LINKMAN WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql, new String[] { linkMain.getId() });

			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();

				contentValues.put("ID", linkMain.getId());
				contentValues.put("REALNAME", linkMain.getRealName());
				contentValues.put("SEX", linkMain.getSex());

				if (CharsetUtil.isNotNull(linkMain.getTel())) {
					contentValues.put("TEL", linkMain.getTel());
				} else {
					contentValues.putNull("TEL");
				}

				if (CharsetUtil.isNotNull(linkMain.getMobile())) {
					contentValues.put("MOBILE", linkMain.getMobile());
				} else {
					contentValues.putNull("MOBILE");
				}

				if (CharsetUtil.isNotNull(linkMain.getDepartmentName())) {
					contentValues.put("DEPARTMENT_NAME",
							linkMain.getDepartmentName());
				} else {
					contentValues.putNull("DEPARTMENT_NAME");
				}

				if (CharsetUtil.isNotNull(linkMain.getPost())) {
					contentValues.put("POST", linkMain.getPost());
				} else {
					contentValues.putNull("POST");
				}

				contentValues.put("RANK", linkMain.getRank());

				if (linkMain.getLongitude() != null) {
					contentValues.put("LONGITUDE", linkMain.getLongitude());
				} else {
					contentValues.putNull("LONGITUDE");
				}

				if (linkMain.getLatitude() != null) {
					contentValues.put("LATITUDE", linkMain.getLatitude());
				} else {
					contentValues.putNull("LATITUDE");
				}

				contentValues.put("REGION_CODE", linkMain.getRegionCode());

				// contentValues.put("ADDTIME", linkMain.getAddTime());
				// contentValues.put("MODIFYTIME", linkMain.getModifyTime());
				// contentValues.put("DELETETIME", linkMain.getDeleteTime());

				if (CharsetUtil.isNotNull(linkMain.getAddTime())) {
					contentValues.put("ADDTIME", linkMain.getAddTime());
				}

				if (CharsetUtil.isNotNull(linkMain.getModifyTime())) {
					contentValues.put("MODIFYTIME", linkMain.getModifyTime());
				}

				if (CharsetUtil.isNotNull(linkMain.getDeleteTime())) {
					contentValues.put("DELETETIME", linkMain.getDeleteTime());
				}

				if (count > 0) {
					// 更新
					db.update("LINKMAN", contentValues, "ID = ? ",
							new String[] { linkMain.getId() });
				} else {
					// 插入
					db.insert("LINKMAN", null, contentValues);
				}
			}

			if (cursor != null) {

				cursor.close();
			}

		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 增加任务来源
	 *
	 * @param renWuLaiYuans
	 */
	public void insertRenWuLaiYuan(List<RenWuLaiYuan> renWuLaiYuans) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (RenWuLaiYuan renWuLaiYuan : renWuLaiYuans) {

			contentValues.clear();

			contentValues.put("ID", renWuLaiYuan.getId());
			contentValues.put("NAME", renWuLaiYuan.getName());
			contentValues.put("SORTORDER", renWuLaiYuan.getSortorder());

			db.insert("RENWULAIYUAN", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 查询所有任务来源
	 *
	 * @return
	 */
	public List<RenWuLaiYuan> queryAllRenWuLaiYuan() {

		List<RenWuLaiYuan> renWuLaiYuans = new ArrayList<RenWuLaiYuan>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM RENWULAIYUAN ", null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			renWuLaiYuans.add(new RenWuLaiYuan(id, name, null));
		}

		if (cursor != null) {
			cursor.close();
		}

		return renWuLaiYuans;
	}

	/**
	 * 查询所有检验类别
	 *
	 * @return
	 */
	public List<JianCeLeiBie> queryAllJianYanLeiBie() {

		List<JianCeLeiBie> datas = new ArrayList<JianCeLeiBie>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM JIANCELEIBIE ", null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			datas.add(new JianCeLeiBie(id, name, null));
		}

		if (cursor != null) {
			cursor.close();
		}

		return datas;
	}

	/**
	 * 查询所有产品类别
	 *
	 * @return
	 */
	public List<ChanPinLeiBie> queryAllChanPinLeiBie() {

		List<ChanPinLeiBie> datas = new ArrayList<ChanPinLeiBie>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM CHANPINLEIBIE ", null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			datas.add(new ChanPinLeiBie(id, name, null));
		}

		if (cursor != null) {
			cursor.close();
		}

		return datas;
	}
	public  ChanPinLeiBie queryChanPinLeiBie(String strid) {

		if(strid==null)strid="0";
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT * FROM CHANPINLEIBIE where ID= '"+strid+"'", null);
		ChanPinLeiBie data=null;
		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			// 查询出检查内容的数据
			data=new ChanPinLeiBie(id, name, null);
		}

		if (cursor != null) {
			cursor.close();
		}

		return data;
	}
	/**
	 * 查询所有检测方法
	 *
	 * @return
	 */
	public List<JianCeFangFa> queryAllJianCeFangFa(int chanPinLeiBie) {

		List<JianCeFangFa> datas = new ArrayList<JianCeFangFa>();

		SQLiteDatabase db = getReadableDatabase();

		String sql = "SELECT * FROM JIANCEFANGFA   ";

		switch (chanPinLeiBie) {
			case 1:
			case 2:
			case 5:
			case 6:
				sql = "SELECT * FROM JIANCEFANGFA   WHERE ID = 1";
				break;
			case 3:
			case 4:
				sql = "SELECT * FROM JIANCEFANGFA   WHERE ID = 2";
				break;
		}

		Cursor cursor = db.rawQuery(sql, null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			datas.add(new JianCeFangFa(id, name, null));
		}

		if (cursor != null) {
			cursor.close();
		}

		return datas;
	}

	/**
	 * 查询所有检测方法
	 *
	 * @return
	 */
	public List<JianCeYiJu> queryAllJianCeYiJu(int chanPinLeiBieId,
											   int jianCeFangFaId) {

		List<JianCeYiJu> datas = new ArrayList<JianCeYiJu>();

		SQLiteDatabase db = getReadableDatabase();

		String sql = "SELECT * FROM JIANCEYIJU ";

		switch (chanPinLeiBieId) {
			case 1:
			case 2:
			case 5:
			case 6:

				if (jianCeFangFaId == 1) {

					sql = "SELECT * FROM JIANCEYIJU   WHERE ID = 1";

				}

				break;
			case 3:
			case 4:
				if (jianCeFangFaId == 2 && chanPinLeiBieId == 3) {

					sql = "SELECT * FROM JIANCEYIJU   WHERE ID IN (2,3) ";

				}

				if (jianCeFangFaId == 2 && chanPinLeiBieId == 4) {

					sql = "SELECT * FROM JIANCEYIJU   WHERE ID = 4 ";

				}

				break;

		}

		Cursor cursor = db.rawQuery(sql, null);

		while (cursor.moveToNext()) {
			Integer id = cursor.getInt(cursor.getColumnIndex("ID"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			// 查询出检查内容的数据
			datas.add(new JianCeYiJu(id, name, null));
		}

		if (cursor != null) {
			cursor.close();
		}

		return datas;
	}

	/**
	 * 增加检测类别
	 *
	 * @param jianCeLeiBies
	 */
	public void insertJianCeLeiBie(List<JianCeLeiBie> jianCeLeiBies) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (JianCeLeiBie jianCeLeiBie : jianCeLeiBies) {

			contentValues.clear();

			contentValues.put("ID", jianCeLeiBie.getId());
			contentValues.put("NAME", jianCeLeiBie.getName());
			contentValues.put("SORTORDER", jianCeLeiBie.getSortorder());

			db.insert("JIANCELEIBIE", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 增加产品类别
	 *
	 * @param chanPinLeiBies
	 */
	public void insertChanPinLeiBie(List<ChanPinLeiBie> chanPinLeiBies) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (ChanPinLeiBie chanPinLeiBie : chanPinLeiBies) {

			contentValues.clear();

			contentValues.put("ID", chanPinLeiBie.getId());
			contentValues.put("NAME", chanPinLeiBie.getName());
			contentValues.put("SORTORDER", chanPinLeiBie.getSortorder());

			db.insert("CHANPINLEIBIE", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 增加检测方法
	 *
	 * @param jianCeLeiBies
	 */
	public void insertJianCeFangFa(List<JianCeFangFa> jianCeFangFas) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (JianCeFangFa jianCeFangFa : jianCeFangFas) {

			contentValues.clear();

			contentValues.put("ID", jianCeFangFa.getId());
			contentValues.put("NAME", jianCeFangFa.getName());
			contentValues.put("SORTORDER", jianCeFangFa.getSortorder());

			db.insert("JIANCEFANGFA", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	/**
	 * 增加检测依™
	 *
	 * @param jianCeLeiBies
	 */
	public void insertJianCeYiJu(List<JianCeYiJu> jianCeYiJus) {

		SQLiteDatabase db = getWritableDatabase();

		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		for (JianCeYiJu jianCeYiJu : jianCeYiJus) {

			contentValues.clear();

			contentValues.put("ID", jianCeYiJu.getId());
			contentValues.put("NAME", jianCeYiJu.getName());
			contentValues.put("SORTORDER", jianCeYiJu.getSortorder());

			db.insert("JIANCEYIJU", null, contentValues);

		}

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	// /**
	// * 插入产品检测记录
	// */
	// public void insertOrUpdateChanPinJianCeRecord(
	// ChanPinJianCeRecord chanPinJianCeRecord, String username) {
	//
	// if (chanPinJianCeRecord != null) {
	//
	// SQLiteDatabase db = getReadableDatabase();
	//
	// int count = queryCountChanPinJianCeById(
	// chanPinJianCeRecord.getId(), username);
	//
	// // 所有的值
	// ContentValues values = new ContentValues();
	//
	// values.put("USERNAME", username);
	//
	// if (chanPinJianCeRecord.getTowns()[0] != null) {
	//
	// StringBuffer city = new StringBuffer();
	// city.append(chanPinJianCeRecord.getTowns()[0].getCode());
	//
	// city.append(",");
	//
	// city.append(chanPinJianCeRecord.getTowns()[0].getName());
	//
	// values.put("CITY", city.toString());
	// } else {
	// values.putNull("CITY");
	// }
	//
	// if (chanPinJianCeRecord.getTowns()[1] != null) {
	//
	// StringBuffer area = new StringBuffer();
	// area.append(chanPinJianCeRecord.getTowns()[1].getCode());
	//
	// area.append(",");
	//
	// area.append(chanPinJianCeRecord.getTowns()[1].getName());
	//
	// values.put("AREA", area.toString());
	//
	// } else {
	// values.putNull("AREA");
	// }
	//
	// if (chanPinJianCeRecord.getTowns()[2] != null) {
	//
	// StringBuffer town = new StringBuffer();
	// town.append(chanPinJianCeRecord.getTowns()[2].getCode());
	//
	// town.append(",");
	//
	// town.append(chanPinJianCeRecord.getTowns()[2].getName());
	//
	// values.put("TOWN", town.toString());
	// } else {
	// values.putNull("TOWN");
	// }
	//
	// // 检验机构
	// if (chanPinJianCeRecord.getChouYanJiGou() != null) {
	//
	// StringBuffer chouYangJiGous = new StringBuffer();
	//
	// ChouYanJiGou chouYangJiGou = chanPinJianCeRecord
	// .getChouYanJiGou();
	//
	// chouYangJiGous.append(chouYangJiGou.getId() + "");
	// chouYangJiGous.append(",");
	//
	// chouYangJiGous.append(chouYangJiGou.getName());
	// chouYangJiGous.append(",");
	// chouYangJiGous.append(chouYangJiGou.isAllowRemove());
	// chouYangJiGous.append(",");
	// chouYangJiGous.append(chouYangJiGou.getTel());
	//
	// values.put("CHOUYANJIGOU", chouYangJiGous.toString());
	//
	// } else {
	// values.putNull("CHOUYANJIGOU");
	// }
	//
	// // 抽验人员
	// if (chanPinJianCeRecord.getChouYangRenYuans() != null
	// && chanPinJianCeRecord.getChouYangRenYuans().size() > 0) {
	//
	// StringBuffer chouYangRenYuans = new StringBuffer();
	//
	// for (int i = 0; i < chanPinJianCeRecord.getChouYangRenYuans()
	// .size(); i++) {
	//
	// JianChaRenYuan chouYangRenYuan = chanPinJianCeRecord
	// .getChouYangRenYuans().get(i);
	//
	// if (chouYangRenYuan.getId() != null) {
	//
	// chouYangRenYuans.append(chouYangRenYuan.getId());
	// chouYangRenYuans.append(",");
	// }
	//
	// chouYangRenYuans.append(chouYangRenYuan.getName());
	//
	// chouYangRenYuans.append(",");
	// chouYangRenYuans.append(chouYangRenYuan.isAllowRemove());
	//
	// chouYangRenYuans.append("#");
	//
	// }
	//
	// if (chouYangRenYuans.length() > 0) {
	// // 清除最后一个字符
	// chouYangRenYuans
	// .deleteCharAt(chouYangRenYuans.length() - 1);
	// }
	//
	// values.put("CHOUYANRENYUAN", chouYangRenYuans.toString());
	//
	// } else {
	// values.putNull("CHOUYANRENYUAN");
	// }
	//
	// // 受检单位
	// if (chanPinJianCeRecord.getShouJianDanWei() != null
	// && !"".equals(chanPinJianCeRecord.getShouJianDanWei()
	// .getName())) {
	//
	// StringBuffer shouJianDanWeis = new StringBuffer();
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .getId());
	//
	// shouJianDanWeis.append(",");
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .getName());
	//
	// shouJianDanWeis.append(",");
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .isCreateShouJianDanWei());
	//
	// shouJianDanWeis.append(",");
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .getAddress());
	//
	// shouJianDanWeis.append(",");
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .getCharge());
	//
	// shouJianDanWeis.append(",");
	//
	// shouJianDanWeis.append(chanPinJianCeRecord.getShouJianDanWei()
	// .getMobile());
	//
	// values.put("SHOUJIANDANWEI", shouJianDanWeis.toString());
	//
	// } else {
	// values.putNull("SHOUJIANDANWEI");
	// }
	//
	// // 任务来源
	// if (chanPinJianCeRecord.getRenWuLaiYuan() != null) {
	//
	// StringBuffer renWuLaiYuans = new StringBuffer();
	//
	// RenWuLaiYuan renWuLaiYuan = chanPinJianCeRecord
	// .getRenWuLaiYuan();
	//
	// renWuLaiYuans.append(renWuLaiYuan.getId());
	// renWuLaiYuans.append(",");
	// renWuLaiYuans.append(renWuLaiYuan.getName());
	//
	// values.put("RENWULAIYUAN", renWuLaiYuans.toString());
	//
	// } else {
	// values.putNull("RENWULAIYUAN");
	// }
	//
	// // 检测类别
	// if (chanPinJianCeRecord.getJianCeLeiBie() != null) {
	//
	// StringBuffer jianCeLeiBies = new StringBuffer();
	//
	// JianCeLeiBie jianCeLeiBie = chanPinJianCeRecord
	// .getJianCeLeiBie();
	//
	// jianCeLeiBies.append(jianCeLeiBie.getId());
	// jianCeLeiBies.append(",");
	// jianCeLeiBies.append(jianCeLeiBie.getName());
	//
	// values.put("JIANCELEIBIE", jianCeLeiBies.toString());
	//
	// } else {
	// values.putNull("JIANCELEIBIE");
	// }
	//
	// // 产品类别
	// if (chanPinJianCeRecord.getChanPinLeiBie() != null) {
	//
	// StringBuffer chanPinLeiBies = new StringBuffer();
	//
	// ChanPinLeiBie chanPinLeiBie = chanPinJianCeRecord
	// .getChanPinLeiBie();
	//
	// chanPinLeiBies.append(chanPinLeiBie.getId());
	// chanPinLeiBies.append(",");
	// chanPinLeiBies.append(chanPinLeiBie.getName());
	//
	// values.put("CHANPINLEIBIE", chanPinLeiBies.toString());
	//
	// } else {
	// values.putNull("CHANPINLEIBIE");
	//
	// }
	//
	// // 检测方法
	// if (chanPinJianCeRecord.getJianCeFangFa() != null) {
	//
	// StringBuffer jianCeFangFas = new StringBuffer();
	//
	// JianCeFangFa jianCeFangFa = chanPinJianCeRecord
	// .getJianCeFangFa();
	//
	// jianCeFangFas.append(jianCeFangFa.getId());
	// jianCeFangFas.append(",");
	// jianCeFangFas.append(jianCeFangFa.getName());
	//
	// values.put("JIANCEFANGFA", jianCeFangFas.toString());
	//
	// } else {
	// values.putNull("JIANCEFANGFA");
	// }
	//
	// // 检测依据
	// if (chanPinJianCeRecord.getJianCeYiJu() != null) {
	//
	// StringBuffer jianCeYiJus = new StringBuffer();
	//
	// JianCeYiJu jianCeYiJu = chanPinJianCeRecord.getJianCeYiJu();
	//
	// jianCeYiJus.append(jianCeYiJu.getId());
	// jianCeYiJus.append(",");
	// jianCeYiJus.append(jianCeYiJu.getName());
	//
	// values.put("JIANCEYIJU", jianCeYiJus.toString());
	//
	// } else {
	// values.putNull("JIANCEYIJU");
	// }
	//
	// // 签名
	// if (chanPinJianCeRecord.getQianMingPath() != null
	// && !"".equals(chanPinJianCeRecord.getQianMingPath())) {
	// values.put("QIANMING", chanPinJianCeRecord.getQianMingPath());
	// } else {
	// values.putNull("QIANMING");
	// }
	//
	// values.put("STATE", chanPinJianCeRecord.getState());
	//
	// values.put("TIME", chanPinJianCeRecord.getTime());
	//
	// // 清空照片
	// deletePhotoByRecordIdFromChanPinJianCe(chanPinJianCeRecord.getId());
	//
	// // 清空样品
	// deleteYangPinByChanPinJianCeId(chanPinJianCeRecord.getId());
	//
	// if (count > 0) {
	//
	// // 存在这条记录,则更新
	// db.update("CHANPINJIANCERECORD", values, "ID = ?",
	// new String[] { chanPinJianCeRecord.getId() });
	//
	// } else {
	//
	// values.put("ID", chanPinJianCeRecord.getId());
	//
	// db.insert("CHANPINJIANCERECORD", null, values);
	//
	// }
	//
	// // 插入所有的照片
	// insertPhotosFromChanPinJianCe(chanPinJianCeRecord.getPhotos(),
	// chanPinJianCeRecord.getId());
	//
	// insertYangPin(chanPinJianCeRecord.getYangPins(),
	// chanPinJianCeRecord.getId());
	// }
	//
	// }

	/**
	 * 查询产品检测
	 *
	 * @return
	 */
	public List<ChanPinJianCeRecord> queryChanPinJianCeRecordByState(
			SQLiteDatabase db, int state, String username) {

		List<ChanPinJianCeRecord> records = new ArrayList<ChanPinJianCeRecord>();

		// 查询出状态为缓存的
		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM CHANPINJIANCERECORD WHERE STATE = ? AND USERNAME = ? ORDER BY TIME DESC ",
						new String[] { String.valueOf(state), username });

		while (cursor.moveToNext()) {

			ChanPinJianCeRecord chanPinJianCeRecord = new ChanPinJianCeRecord();

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			// 设置ID
			chanPinJianCeRecord.setId(id);

			String cityInfo = cursor.getString(cursor.getColumnIndex("CITY"));

			if (CharsetUtil.isNotNull(cityInfo)) {

				String[] cityInfoArr = cityInfo.split(",");

				if (cityInfoArr.length == 2) {

					Town city = new Town(cityInfoArr[0], null, null,
							cityInfoArr[1]);

					chanPinJianCeRecord.getTowns()[0] = city;
				}

			}

			String areaInfo = cursor.getString(cursor.getColumnIndex("AREA"));

			if (CharsetUtil.isNotNull(areaInfo)) {

				String[] areaInfos = areaInfo.split(",");

				if (areaInfos.length == 2) {

					Town area = new Town(areaInfos[0], null, null, areaInfos[1]);

					chanPinJianCeRecord.getTowns()[1] = area;
				}

			}

			String townInfo = cursor.getString(cursor.getColumnIndex("TOWN"));

			if (CharsetUtil.isNotNull(townInfo)) {

				String[] townInfos = townInfo.split(",");

				if (townInfos.length == 2) {

					Town town = new Town(townInfos[0], null, null, townInfos[1]);

					chanPinJianCeRecord.getTowns()[2] = town;
				}

			}

			// 获取抽样机构
			String chouYangJiGouInfo = cursor.getString(cursor
					.getColumnIndex("CHOUYANJIGOU"));

			if (CharsetUtil.isNotNull(chouYangJiGouInfo)) {

				String[] chouYangJiGouInfoArr = chouYangJiGouInfo.split(",");

				ChouYanJiGou chouYangJiGou = new ChouYanJiGou(
						chouYangJiGouInfoArr[0], chouYangJiGouInfoArr[1]);

				if (chouYangJiGouInfoArr.length == 3) {
					chouYangJiGou.setAllowRemove(Boolean
							.parseBoolean(chouYangJiGouInfoArr[2]));
				}

				if (chouYangJiGouInfoArr.length == 4) {

					chouYangJiGou.setTel(chouYangJiGouInfoArr[3]);

				}

				chanPinJianCeRecord.setChouYanJiGou(chouYangJiGou);

			}

			// 获取抽样人员
			String chouYangRenYuanInfo = cursor.getString(cursor
					.getColumnIndex("CHOUYANRENYUAN"));

			if (CharsetUtil.isNotNull(chouYangRenYuanInfo)) {

				String[] chouYangRenYuanInfos = chouYangRenYuanInfo.split("#");

				for (String chouYangRenYuanF : chouYangRenYuanInfos) {

					String[] chouYangRenYuanInfoArr = chouYangRenYuanF
							.split(",");

					JianChaRenYuan jianChaRenYuan = new JianChaRenYuan(
							chouYangRenYuanInfoArr[0],
							chouYangRenYuanInfoArr[1], null);

					jianChaRenYuan.setAllowRemove(Boolean
							.parseBoolean(chouYangRenYuanInfoArr[2]));

					chanPinJianCeRecord.getChouYangRenYuans().add(
							jianChaRenYuan);

				}
			}

			// 获取受检单位
			String shouJianDanWeiInfo = cursor.getString(cursor
					.getColumnIndex("SHOUJIANDANWEI"));

			if (CharsetUtil.isNotNull(shouJianDanWeiInfo)) {

				String[] shouJianDanWeiInfos = shouJianDanWeiInfo.split(",");

				BeiJianDanWei shouJianDanWei = new BeiJianDanWei(
						shouJianDanWeiInfos[0], shouJianDanWeiInfos[1]);

				boolean isCreateShouJianDanWei = Boolean
						.parseBoolean(shouJianDanWeiInfos[2]);

				shouJianDanWei.setCreateShouJianDanWei(isCreateShouJianDanWei);

				String address = null;

				String charge = null;

				String mobile = null;

				try {
					address = shouJianDanWeiInfos[3];
					charge = shouJianDanWeiInfos[4];
					mobile = shouJianDanWeiInfos[5];
				} catch (ArrayIndexOutOfBoundsException e) {

				}

				shouJianDanWei.setAddress(address);

				shouJianDanWei.setCharge(charge);

				shouJianDanWei.setMobile(mobile);

				chanPinJianCeRecord.setShouJianDanWei(shouJianDanWei);

			}

			// 获取任务来源
			String renWuLaiYuanInfo = cursor.getString(cursor
					.getColumnIndex("RENWULAIYUAN"));

			if (CharsetUtil.isNotNull(renWuLaiYuanInfo)) {

				String[] renWuLaiYuanInfoArr = renWuLaiYuanInfo.split(",");

				RenWuLaiYuan renWuLaiYuan = new RenWuLaiYuan(
						Integer.parseInt(renWuLaiYuanInfoArr[0]),
						renWuLaiYuanInfoArr[1], null);

				chanPinJianCeRecord.setRenWuLaiYuan(renWuLaiYuan);

			}

			// 获取检测类别
			String jianCeLeiBieInfo = cursor.getString(cursor
					.getColumnIndex("JIANCELEIBIE"));

			if (CharsetUtil.isNotNull(jianCeLeiBieInfo)) {

				String[] jianCeLeiBieInfoArr = jianCeLeiBieInfo.split(",");

				JianCeLeiBie jianCeLeiBie = new JianCeLeiBie(
						Integer.parseInt(jianCeLeiBieInfoArr[0]),
						jianCeLeiBieInfoArr[1], null);

				chanPinJianCeRecord.setJianCeLeiBie(jianCeLeiBie);
			}

			// 获取产品类别
			String chanPinLeiBieInfo = cursor.getString(cursor
					.getColumnIndex("CHANPINLEIBIE"));

			if (CharsetUtil.isNotNull(chanPinLeiBieInfo)) {

				String[] chanPinLeiBieInfoArr = chanPinLeiBieInfo.split(",");

				ChanPinLeiBie chanPinLeiBie = new ChanPinLeiBie(
						Integer.parseInt(chanPinLeiBieInfoArr[0]),
						chanPinLeiBieInfoArr[1], null);

				chanPinJianCeRecord.setChanPinLeiBie(chanPinLeiBie);

			}

			// 获取检测方法
			String jianCeFangFaInfo = cursor.getString(cursor
					.getColumnIndex("JIANCEFANGFA"));

			if (CharsetUtil.isNotNull(jianCeFangFaInfo)) {

				String[] jianCeFangFaInfoArr = jianCeFangFaInfo.split(",");

				JianCeFangFa jianCeFangFa = new JianCeFangFa(
						Integer.parseInt(jianCeFangFaInfoArr[0]),
						jianCeFangFaInfoArr[1], null);

				chanPinJianCeRecord.setJianCeFangFa(jianCeFangFa);

			}

			// 获取检测依据
			String jianCeYiJuInfo = cursor.getString(cursor
					.getColumnIndex("JIANCEYIJU"));

			if (CharsetUtil.isNotNull(jianCeYiJuInfo)) {

				String[] jianCeYiJuInfoArr = jianCeYiJuInfo.split(",");

				JianCeYiJu jianCeYiJu = new JianCeYiJu(
						Integer.parseInt(jianCeYiJuInfoArr[0]),
						jianCeYiJuInfoArr[1], null);

				chanPinJianCeRecord.setJianCeYiJu(jianCeYiJu);

			}

			// �@取�名
			String qianMingPath = cursor.getString(cursor
					.getColumnIndex("QIANMING"));

			if (CharsetUtil.isNotNull(qianMingPath)) {

				chanPinJianCeRecord.setQianMingPath(qianMingPath);
			}

			// �@取r�g
			String time = cursor.getString(cursor.getColumnIndex("TIME"));

			chanPinJianCeRecord.setTime(time);

			// 状态
			chanPinJianCeRecord.setState(state);

			// 还原照片
			ArrayList<Photo> photos = (ArrayList<Photo>) queryPhotoByRecordIdFromChanPinJianCe(
					db, id);

			chanPinJianCeRecord.setPhotos(photos);

			// 还原样品
			ArrayList<YangPin> yangPins = (ArrayList<YangPin>) queryYangPinByChanPinJianCeId(
					db, id);

			chanPinJianCeRecord.setYangPins(yangPins);

			// 还原用户名
			chanPinJianCeRecord.setUsername(username);

			records.add(chanPinJianCeRecord);
		}

		if (cursor != null) {
			cursor.close();
		}

		return records;
	}

	public void insertYangPin(List<YangPin> yangPins, String recordId) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		for (YangPin yangPin : yangPins) {

			ContentValues contentValues = new ContentValues();

			contentValues.put("ID", yangPin.getId());
			contentValues.put("SUFSTRING", yangPin.getBianHao().getSufString());
			contentValues.put("BIANHAO1", yangPin.getBianHao().getBianHao1());
			contentValues.put("BIANHAO2", yangPin.getBianHao().getBianHao2());
			contentValues.put("NAME", yangPin.getName());
			contentValues.put("LOCALE", yangPin.getLocale());
			contentValues.put("JISHU", yangPin.getJiShu());
			contentValues.put("XINGHAO", yangPin.getXingHao());
			contentValues.put("CHANPINJIANCE_ID", recordId);

			db.insert("CHANPINJIANCE", null, contentValues);
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	public List<YangPin> queryYangPinByChanPinJianCeId(SQLiteDatabase db,
													   String recordId) {

		List<YangPin> yangPins = new ArrayList<YangPin>();

		String sql = "SELECT *  FROM CHANPINJIANCE WHERE CHANPINJIANCE_ID = ?";

		Cursor cursor = db.rawQuery(sql, new String[] { recordId });

		while (cursor.moveToNext()) {

			YangPin yangPin = new YangPin();

			String id = cursor.getString(cursor.getColumnIndex("ID"));
			String sufString = cursor.getString(cursor
					.getColumnIndex("SUFSTRING"));
			String bianHao1 = cursor.getString(cursor
					.getColumnIndex("BIANHAO1"));
			String bianHao2 = cursor.getString(cursor
					.getColumnIndex("BIANHAO2"));
			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			String locale = cursor.getString(cursor.getColumnIndex("LOCALE"));
			String jishu = cursor.getString(cursor.getColumnIndex("JISHU"));
			String xinghao = cursor.getString(cursor.getColumnIndex("XINGHAO"));

			YangPinBianHao bianHao = new YangPinBianHao(sufString, bianHao1,
					bianHao2);

			yangPin.setBianHao(bianHao);

			yangPin.setId(id);

			yangPin.setName(name);

			yangPin.setLocale(locale);

			yangPin.setJiShu(jishu);

			yangPin.setXingHao(xinghao);

			yangPins.add(yangPin);

		}

		if (cursor != null) {
			cursor.close();
		}
		return yangPins;
	}

	public void deleteYangPinByChanPinJianCeId(String recordId) {
		SQLiteDatabase db = getReadableDatabase();

		db.delete("CHANPINJIANCE", "CHANPINJIANCE_ID = ?",
				new String[] { recordId });

	}

	public void insertOrUpdateDuChaXunCha(List<DuChaXunCha> duChaXunChas) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		/**
		 * 遍历所有检查单位
		 */
		for (DuChaXunCha duChaXunCha : duChaXunChas) {

			String sql = "SELECT COUNT(*) FROM DUCHAXUNCHA WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { duChaXunCha.getRegion_code() });
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				ContentValues contentValues = new ContentValues();
				contentValues.put("REGION_CODE", duChaXunCha.getRegion_code());
				contentValues.put("TITLE", duChaXunCha.getTitle());
				contentValues.put("PROBLEM", duChaXunCha.getProblem());
				contentValues.put("TRADE", duChaXunCha.getTrade());
				contentValues.put("KEY", duChaXunCha.getKey());
				if (CharsetUtil.isNotNull(duChaXunCha.getAddTime())) {
					contentValues.put("ADDTIME", duChaXunCha.getAddTime());
				}

				if (CharsetUtil.isNotNull(duChaXunCha.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							duChaXunCha.getModifyTime());
				}

				if (CharsetUtil.isNotNull(duChaXunCha.getDeleteTime())) {
					contentValues.put("DELETETIME",
							duChaXunCha.getDeleteTime());
				}

				if (count > 0) {
					// 更新
					db.update("DUCHAXUNCHA", contentValues, "REGION_CODE = ? ",
							new String[] { duChaXunCha.getRegion_code()});

				} else {
					// 插入
					db.insert("DUCHAXUNCHA", null, contentValues);
				}

			}
			if (cursor != null)
				cursor.close();
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	public void insertChouYangJiGou(List<ChouYanJiGou> chouYanJiGous,
									SQLiteDatabase db) {

		if (db == null) {
			db = getWritableDatabase();
		}
		ContentValues contentValues = new ContentValues();

		db.beginTransaction();

		/**
		 * 遍历所有检查单位
		 */
		for (ChouYanJiGou chouYanJiGou : chouYanJiGous) {

			contentValues.clear();

			// 插入检查行业

			if (CharsetUtil.isNotNull(chouYanJiGou.getId())) {

				contentValues.put("ID", chouYanJiGou.getId());
			}

			contentValues.put("NAME", chouYanJiGou.getName());
			contentValues.put("CODE", chouYanJiGou.getCode());

			// contentValues.put("ADDTIME", chouYanJiGou.getAddTime());
			// contentValues.put("MODIFYTIME", chouYanJiGou.getModifyTime());
			// contentValues.put("DELETETIME", chouYanJiGou.getDeleteTime());

			if (CharsetUtil.isNotNull(chouYanJiGou.getAddTime())) {
				contentValues.put("ADDTIME", chouYanJiGou.getAddTime());
			}

			if (CharsetUtil.isNotNull(chouYanJiGou.getModifyTime())) {
				contentValues.put("MODIFYTIME", chouYanJiGou.getModifyTime());
			}

			if (CharsetUtil.isNotNull(chouYanJiGou.getDeleteTime())) {
				contentValues.put("DELETETIME", chouYanJiGou.getDeleteTime());
			}

			if (CharsetUtil.isNotNull(chouYanJiGou.getTel())) {

				contentValues.put("TEL", chouYanJiGou.getTel());

			}

			db.insert("CHOUYANJIGOU", null, contentValues);
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 查询所有抽验机构
	 *
	 * @param code
	 * @return
	 */
	public List<ChouYanJiGou> queryAllChouYanJiGou(String code) {

		SQLiteDatabase db = getReadableDatabase();

		List<ChouYanJiGou> chouYanJiGous = new ArrayList<ChouYanJiGou>();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,CODE,TEL FROM ( SELECT ID,NAME ,CODE,TEL FROM CHOUYANJIGOU WHERE CODE = ? ORDER BY CODE ASC   ) UNION ALL SELECT ID,NAME,CODE,TEL FROM (SELECT  ID,NAME ,CODE,TEL  FROM CHOUYANJIGOU WHERE CODE <> ?  AND CODE LIKE ? ORDER BY CODE ASC )",
						new String[] { code, code, code + "%" });
		Log.d("sdk","SELECT ID,NAME,CODE,TEL FROM ( SELECT ID,NAME ,CODE,TEL FROM CHOUYANJIGOU WHERE CODE = ? ORDER BY CODE ASC   ) UNION ALL SELECT ID,NAME,CODE,TEL FROM (SELECT  ID,NAME ,CODE,TEL  FROM CHOUYANJIGOU WHERE CODE <> ?  AND CODE LIKE ? ORDER BY CODE ASC )??"+code);
		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));
			ChouYanJiGou cy=new ChouYanJiGou(id, name, codeVal);
			try{
				cy.setTel( cursor.getString(cursor.getColumnIndex("TEL")));
			}catch(java.lang.Exception e){
				e.printStackTrace();
			}
			chouYanJiGous.add(cy);


		}

		if (cursor != null) {
			cursor.close();
		}

		return chouYanJiGous;
	}

	/**
	 * 根据ID查询抽验机构
	 *
	 * @param id
	 * @return
	 */
	public ChouYanJiGou queryChouYanJiGou(String id) {

		ChouYanJiGou chouYanJiGou = null;

		SQLiteDatabase db = getReadableDatabase();

		List<ChouYanJiGou> chouYanJiGous = new ArrayList<ChouYanJiGou>();

		Cursor cursor = db.rawQuery(
				"SELECT ID,NAME ,CODE,TEL FROM CHOUYANJIGOU WHERE ID = ? ",
				new String[] { id });

		if (cursor.moveToNext()) {

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));
			Log.d("jgtel",tel);
			chouYanJiGou = new ChouYanJiGou(id, name, codeVal, null, null,
					null, tel);
		}

		if (cursor != null) {
			cursor.close();
		}

		return chouYanJiGou;
	}

	/**
	 * 查询所有抽验机构
	 *
	 * @param code
	 * @return
	 */
	public List<ChouYanJiGou> queryAllChouYanJiGou(String code, String filter) {

		SQLiteDatabase db = getReadableDatabase();

		List<ChouYanJiGou> chouYanJiGous = new ArrayList<ChouYanJiGou>();

		Cursor cursor = db
				.rawQuery(
						"SELECT ID,NAME,CODE,TEL FROM ( SELECT ID,NAME ,CODE,TEL FROM CHOUYANJIGOU WHERE CODE = ? AND NAME LIKE ?  ORDER BY CODE ASC   ) UNION ALL SELECT ID,NAME,CODE,TEL FROM (SELECT  ID,NAME ,CODE,TEL  FROM CHOUYANJIGOU WHERE CODE <> ?  AND CODE LIKE ? AND NAME LIKE ? ORDER BY CODE ASC )",
						new String[] { code, "%" + filter + "%", code,
								code + "%", "%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));
			ChouYanJiGou cy=new ChouYanJiGou(id, name, codeVal);
			try{
				cy.setTel( cursor.getString(cursor.getColumnIndex("TEL")));
			}catch(java.lang.Exception e){
				e.printStackTrace();
			}
			chouYanJiGous.add(cy);

		}

		if (cursor != null) {
			cursor.close();
		}

		return chouYanJiGous;
	}

	public List<ChouYanJiGou> queryAllChouYanJiGouNotLike(String code) {

		List<ChouYanJiGou> jianChaDanWeis = new ArrayList<ChouYanJiGou>();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db
				.rawQuery(
						"SELECT * FROM CHOUYANJIGOU WHERE  CODE  = ? ORDER BY CODE ASC",
						new String[] { code });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeVal = cursor.getString(cursor.getColumnIndex("CODE"));

			jianChaDanWeis.add(new ChouYanJiGou(id, name, codeVal));

		}

		if (cursor != null) {
			cursor.close();
		}
		return jianChaDanWeis;
	}

	public void insertOrUpdateChouYangJiGou(List<ChouYanJiGou> chouYanJiGous) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		/**
		 * 遍历所有检查单位
		 */
		for (ChouYanJiGou chouYanJiGou : chouYanJiGous) {

			String sql = "SELECT COUNT(*) FROM CHOUYANJIGOU WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { chouYanJiGou.getId() });

			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();

				contentValues.put("ID", chouYanJiGou.getId());
				contentValues.put("NAME", chouYanJiGou.getName());
				contentValues.put("CODE", chouYanJiGou.getCode());

				if (CharsetUtil.isNotNull(chouYanJiGou.getAddTime())) {
					contentValues.put("ADDTIME", chouYanJiGou.getAddTime());
				}

				if (CharsetUtil.isNotNull(chouYanJiGou.getModifyTime())) {
					contentValues.put("MODIFYTIME",
							chouYanJiGou.getModifyTime());
				}

				if (CharsetUtil.isNotNull(chouYanJiGou.getDeleteTime())) {
					contentValues.put("DELETETIME",
							chouYanJiGou.getDeleteTime());
				}

				if (CharsetUtil.isNotNull(chouYanJiGou.getTel())) {
					contentValues.put("TEL", chouYanJiGou.getTel());
				}

				if (count > 0) {
					// 更新
					db.update("CHOUYANJIGOU", contentValues, "ID = ? ",
							new String[] { chouYanJiGou.getId() });

				} else {
					// 插入
					db.insert("CHOUYANJIGOU", null, contentValues);
				}

			}
			if (cursor != null)
				cursor.close();
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	/**
	 * 查询最大的时间通过表名和列名
	 */

	public String queryMaxMotifyTime(String tableName, String column,
									 String code) {

//		String maxTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//				.format(new Date(0));
		/**
		 * 数据库打包时间
		 */
		String maxTime ="2018-04-23 21:08:01";

		String sql = "SELECT MAX(" + column + ") AS TIME FROM " + tableName
				+ " WHERE CODE||'' LIKE '" + code + "%'";

		if ("LINKMAN".equals(tableName)) {

			sql = "SELECT MAX(" + column + ") AS TIME FROM " + tableName
					+ " WHERE REGION_CODE||'' LIKE '" + code + "%'";
		}

		if ("TOWN".equals(tableName)) {
			sql = "SELECT MAX(" + column + ") AS TIME FROM " + tableName;

		}
		if("DUCHAXUNCHA".equals(tableName)){
			sql = "SELECT MAX(" + column + ") AS TIME FROM " + tableName;
		}
		if("BEIJIANDANWEI".equals(tableName)){
			sql ="SELECT datetime("+column+") AS TIME1,ADDTIME AS TIME  from  BEIJIANDANWEI WHERE CODE ||'' LIKE '" + code + "%'  ORDER BY TIME1 DESC LIMIT 0,1";
		}


		if("MONITOR_PLAN".equals(tableName)){
			sql ="SELECT datetime("+column+") AS TIME1,"+column+" AS TIME  from  MONITOR_PLAN WHERE REGION ||'' LIKE '" + code + "%'  ORDER BY TIME1 DESC LIMIT 0,1";
		}


		Log.d("time sql",sql);
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(sql, null);

		while (cursor.moveToNext()) {

			String maxTimeRes = cursor.getString(cursor.getColumnIndex("TIME"));

			if (CharsetUtil.isNotNull(maxTimeRes)) {
				maxTime = maxTimeRes;
			}

		}

		if (cursor != null) {
			cursor.close();
		}

		return maxTime;
	}

	public void deleteRecord(String tableName, String columnName,
							 List<String> in, Map<String, String> times) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		String sql = "DELETE FROM " + tableName + " WHERE " + columnName
				+ " IN (";

		for (int i = 0; i < in.size(); i++) {
			String inItem = in.get(i);

			sql += "'" + inItem + "'";

			if (i < in.size() - 1) {

				sql += ",";

			}

		}

		sql += ")";
		Log.d("rafe sql delect",sql);
		db.execSQL(sql);

		sql = "UPDATE " + tableName + " SET ";

		for (Entry<String, String> entry : times.entrySet()) {

			String column = entry.getKey();

			String val = entry.getValue();

			sql += column + " = " + "'" + val + "'" + " ,";
		}

		if (sql.endsWith(",")) {
			sql = sql.substring(0, sql.length() - 1);
		}

		db.execSQL(sql);

		db.setTransactionSuccessful();

		db.endTransaction();
	}


	public void test(String tablename) {

		SQLiteDatabase db = getReadableDatabase();


		String sql="SELECT * FROM "+tablename+" BJDW LIMIT 0,10";

		Cursor cursor = db.rawQuery(
				sql,
				new String[] {});

		Log.d("rafe test sql",sql);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("NAME"));
			Log.d("rafe test echo",name+" >>"+cursor.getString(cursor.getColumnIndex("ADDTIME")));

		}

		if (cursor != null) {
			cursor.close();
		}


	}

	/**rafe add 添加或更新计划*/
	public void insertOrUpdateMoinitorPlan(
			JSONArray list,String opt) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		for (int i=0;i<list.length();i++) {
			JSONObject plan=list.optJSONObject(i);
			String sql = "SELECT COUNT(*) FROM MONITOR_PLAN WHERE ID = ?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { plan.optString("id","0") });

			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();


				// 插入检查人员
				contentValues.put("ID", plan.optString("id",""));
				contentValues.put("REGION", plan.optString("ent_area",""));
				contentValues.put("NAME", plan.optString("name",""));
				contentValues.put("BEGIN_DATE", plan.optString("begin_date",""));
				contentValues.put("END_DATE", plan.optString("end_date",""));
				contentValues.put("ENT_AREA", plan.optString("ent_area",""));
				contentValues.put("ENT_KINDS", plan.optString("ent_kind",""));

				contentValues.put("ENT_PRODUCES", plan.optString("ent_produce",""));

				contentValues.put("ENT_NAME_LIKE", plan.optString("ent_name_like",""));
				contentValues.put("APPOINT_ENT", plan.optString("appoint_ent",""));
				contentValues.put("PRODUCT_NAME_LIKE","");
				contentValues.put("ENT_CATEGORYS",plan.optString("ent_trade",""));


				if(opt.equals("add")){
					contentValues.put("ADDTIME", plan.optString("add_time",""));
				}
				if(opt.equals("modify")){
					contentValues.put("MODIFYTIME",plan.optString("modify_time",""));
				}
				contentValues.put("DELETETIME",plan.optString("delete_time",""));


				if (count > 0) {
					// 更新
					Log.d("rafe MONITOR_PLAN update",plan.optString("id",""));
					db.update("MONITOR_PLAN", contentValues, "ID = ? ",
							new String[] { plan.optString("id","") });

				} else {
					// 插入
					Log.d("rafe MONITOR_PLAN insert",plan.optString("id",""));
					db.insert("MONITOR_PLAN", null, contentValues);
				}
			}

			if (cursor != null)
				cursor.close();
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}

	public void updateRegionCount4(){
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		List<Town> towns =queryTownByWhere(" LENGTH (CODE)=6 ");
		for(int i=0;i<towns.size();i++){
			ContentValues contentValues = new ContentValues();
			String sql = "select SUM(TOWN.CNT)  from TOWN where CODE LIKE '3204%' AND  LENGTH(CODE)=6";
			Cursor cursor = db.rawQuery(sql,
					new String[] { });
			if (cursor.moveToNext()){
				contentValues.put("CNT",cursor.getInt(0));
			}
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {"3204"});
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}
	public void updateRegionCount6(){
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		List<Town> towns =queryTownByWhere(" LENGTH (CODE)=6 ");
		for(int i=0;i<towns.size();i++){
			ContentValues contentValues = new ContentValues();
			String sql = "select SUM(TOWN.CNT)  from TOWN where CODE LIKE '"+towns.get(i).getCode()+"%' AND  LENGTH(CODE)=8";
			Cursor cursor = db.rawQuery(sql,
					new String[] { });
			if (cursor.moveToNext()){
				contentValues.put("CNT",cursor.getInt(0));
			}
			if(cursor!=null)
				cursor.close();
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {towns.get(i).getCode() });
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}


	public void updateCount(List<Town> towns){
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();

		for(int i=0;i<towns.size();i++){
			ContentValues contentValues = new ContentValues();
			contentValues.put("CNT",towns.get(i).getBeijiandanwei());
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {towns.get(i).getCode() });
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	public List<Town>   findEntCounts(List<Town> towns){
		String table="";
		SQLiteDatabase db =  getReadableDatabase();

		for(int i=0;i<towns.size();i++){
			String code=towns.get(i).getCode();
			if(code.length()>6){
				table=code.substring(0, 8);
				String sql = "SELECT COUNT(1) FROM BEIJIANDANWEI"+table+" where CODE LIKE '"+code+"%'";
				Cursor   cursor = db.rawQuery(sql,new String[] { });
				if (cursor.moveToNext()){
					towns.get(i).setBeijiandanwei(cursor.getInt(0));
				}
				if(cursor!=null)cursor.close();
			}
		}

		return towns;

	}
	public int findEntCount(String code){
		String table="";
		if(code.length()>6){
			table=code.substring(0, 8);
		}else{
			return 0;
		}
		SQLiteDatabase db =  getReadableDatabase();

		String sql = "SELECT COUNT(1) FROM BEIJIANDANWEI"+table+" where CODE LIKE '"+code+"%'";
		Cursor cursor = db.rawQuery(sql,
				new String[] { });
		int i=0;
		if (cursor.moveToNext()){
			i=cursor.getInt(0);
		}
		if(cursor!=null)cursor.close();
		return i;

	}

	private int getEntCount(String code){
		if(code.length()>6){
			code=code.substring(0, 8);
		}else{
			return 0;
		}
		SQLiteDatabase db = getWritableDatabase();
		String sql = "SELECT COUNT(*) FROM BEIJIANDANWEI"+code;
		Cursor cursor = db.rawQuery(sql,
				new String[] { });
		int i=0;
		if (cursor.moveToNext()){
			i=cursor.getInt(0);
		}
		if(cursor!=null)cursor.close();
		return i;

	}

	public void updateReginCount14() {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		List<Town> towns =queryTownByWhere(" LENGTH (CODE)= 14");
		for(int i=0;i<towns.size();i++){
			String code=towns.get(i).getCode();
			int bj=this.getEntCount(code);
			ContentValues contentValues = new ContentValues();
			contentValues.put("CNT",bj);
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {code});
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}
	public void updateReginCount(int cline) {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		List<Town> towns =queryTownByWhere(" LENGTH (CODE)= "+cline);
		for(int i=0;i<towns.size();i++){
			String code=towns.get(i).getCode();
			Log.d("rafe code",code+"?length="+cline);
			int bj=this.getEntCount(code);
			ContentValues contentValues = new ContentValues();

			String sql = "select SUM(TOWN.CNT)  from TOWN where CODE LIKE '"+code+"%' AND  LENGTH (CODE)="+(cline+2);
			Cursor cursor = db.rawQuery(sql,
					new String[] {});
			if (cursor.moveToNext()){
				contentValues.put("CNT",cursor.getInt(0)+bj);
			}
			if(cursor!=null)
				cursor.close();
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {code});
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}
	public void updateReginCount0421(JSONArray datas) {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();

		for(int i=0;i<datas.length();i++){
			JSONObject code=datas.optJSONObject(i);
			ContentValues contentValues = new ContentValues();
			contentValues.put("CNT",code.optString("CNT","0"));
			db.update("TOWN", contentValues, "CODE = ? ",
					new String[] {code.optString("CODE")});
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}
	/**xrf 计划列表*/
	public List<Plan> queryAllPlan(String filter, String code,int page) {

		List<Plan> beiJianDanWeis = new ArrayList<Plan>();

		SQLiteDatabase db = getReadableDatabase();
		String sql="SELECT * FROM MONITOR_PLAN WHERE REGION LIKE '"+code+"%' AND  NAME LIKE ?";
		sql+=" limit "+(page*SPAN)+","+SPAN;
		Cursor cursor = db
				.rawQuery(sql,new String[] { "%" + filter + "%" });
		Log.d("rafe_plan",sql+"?code="+code);

		//		   String sql="SELECT * FROM MONITOR_PLAN ";
		//	Cursor cursor = db
		//			.rawQuery(sql,new String[] {});
		Log.d("rafe_plan",sql+"?code="+code);
		while (cursor.moveToNext()) {

			Plan plan=new Plan();
			plan.setBeginDate(cursor.getString(cursor.getColumnIndex("BEGIN_DATE")));
			plan.setEndDate(cursor.getString(cursor.getColumnIndex("END_DATE")));
			plan.setEntArea(cursor.getString(cursor.getColumnIndex("ENT_AREA")));
			plan.setEntCategorys(cursor.getString(cursor.getColumnIndex("ENT_CATEGORYS")));
			plan.setEntCount(cursor.getInt(cursor.getColumnIndex("APPOINT_ENT")));
			plan.setEntKinds(cursor.getString(cursor.getColumnIndex("ENT_KINDS")));
			plan.setEntNameLike(cursor.getString(cursor.getColumnIndex("ENT_NAME_LIKE")));
			plan.setEntProduces(cursor.getString(cursor.getColumnIndex("ENT_PRODUCES")));
			plan.setId(cursor.getString(cursor.getColumnIndex("ID")));
			plan.setName(cursor.getString(cursor.getColumnIndex("NAME")));
			plan.setProductNameLike(cursor.getString(cursor.getColumnIndex("PRODUCT_NAME_LIKE")));
			plan.setRegion_code(cursor.getString(cursor.getColumnIndex("REGION")));

			beiJianDanWeis.add(plan);


		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}
	/**xrf 计划列表*/
	public void deletePlan(JSONArray datas) {

		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		String sql = "DELETE FROM  MONITOR_PLAN WHERE ID"
				+ " IN (";

		for (int i = 0; i < datas.length(); i++) {
			String inItem = datas.optJSONObject(i).optString("id","0");
			sql += "'" + inItem + "'";

			if (i < datas.length() - 1) {

				sql += ",";

			}

		}

		sql += ")";
		Log.d("rafe_sql_delect_plan",sql);
		db.execSQL(sql);

		db.execSQL(sql);

		db.setTransactionSuccessful();

		db.endTransaction();
	}

	public  Plan  queryPlanByID(String id) {


		SQLiteDatabase db = getReadableDatabase();
		String sql="SELECT * FROM MONITOR_PLAN WHERE ID = ?";

		Cursor cursor = db
				.rawQuery(sql,new String[] {id});
		Plan plan=null;
		if (cursor.moveToNext()) {
			plan=new Plan();
			plan.setBeginDate(cursor.getString(cursor.getColumnIndex("BEGIN_DATE")));
			plan.setEndDate(cursor.getString(cursor.getColumnIndex("END_DATE")));
			plan.setEntArea(cursor.getString(cursor.getColumnIndex("ENT_AREA")));
			plan.setEntCategorys(cursor.getString(cursor.getColumnIndex("ENT_CATEGORYS")));
			plan.setEntCount(cursor.getInt(cursor.getColumnIndex("APPOINT_ENT")));
			plan.setEntKinds(cursor.getString(cursor.getColumnIndex("ENT_KINDS")));
			plan.setEntNameLike(cursor.getString(cursor.getColumnIndex("ENT_NAME_LIKE")));
			plan.setEntProduces(cursor.getString(cursor.getColumnIndex("ENT_PRODUCES")));
			plan.setId(cursor.getString(cursor.getColumnIndex("ID")));
			plan.setName(cursor.getString(cursor.getColumnIndex("NAME")));
			plan.setProductNameLike(cursor.getString(cursor.getColumnIndex("PRODUCT_NAME_LIKE")));
			plan.setRegion_code(cursor.getString(cursor.getColumnIndex("REGION")));
		}

		if (cursor != null) {
			cursor.close();
		}

		return plan;
	}

	/**xrf 计划列表*/
	public JSONArray queryAllPlanEnt(String pid) {

		SQLiteDatabase db = getReadableDatabase();
		String sql="SELECT * FROM PLAN_ENT_IDS WHERE PID= ? ";
		Cursor cursor = db
				.rawQuery(sql,new String[] {pid });
		JSONArray arr=new JSONArray();
		while (cursor.moveToNext()) {
			JSONObject obj=new JSONObject();
			try {
				obj.putOpt("pid",cursor.getString(cursor.getColumnIndex("PID")));

				obj.putOpt("entId",cursor.getString(cursor.getColumnIndex("ENT_ID")));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			arr.put(obj);
		}

		if (cursor != null) {
			cursor.close();
		}

		return arr;
	}
	public List<BeiJianDanWei> queryAllBeiJianDanWieByWhere(String code,int page,String where) {


		Log.d("rafecode",String.valueOf(code));
		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();
		if(code.length()<8){return beiJianDanWeis;
		}
		String tableCode=code.substring(0,8);
		SQLiteDatabase db = getReadableDatabase();
		if(!hasTable("BEIJIANDANWEI"+tableCode)){
			return beiJianDanWeis;
		}

		String sql="SELECT * FROM BEIJIANDANWEI"+tableCode+" BJDW WHERE BJDW.CODE LIKE ? ";

		sql+=" and "+where;
		sql+=" LIMIT "+(page*SPAN)+","+SPAN;
		Cursor cursor = db.rawQuery(
				sql,
				new String[] { code + "%" });


		Log.d("rafe sql beijiandanwei",sql+"?code="+code);
		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}



	public List<BeiJianDanWei> queryAllBeiJianDanWieByWhere(String filter, String code,int page,String where) {

		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();
		if(code.length()<8){return beiJianDanWeis;
		}
		String tableCode=code.substring(0,8);
		SQLiteDatabase db = getReadableDatabase();
		if(!hasTable("BEIJIANDANWEI"+tableCode)){
			return beiJianDanWeis;
		}
		String sql="SELECT * FROM BEIJIANDANWEI"+tableCode+" BJDW WHERE BJDW.CODE LIKE ? AND  BJDW.NAME LIKE ?";
		sql+=" and "+where;
		sql+=" limit "+(page*SPAN)+","+SPAN;

		Log.d("rafe sql beijiandanwei",sql+"?code="+code);
		Cursor cursor = db
				.rawQuery(sql,new String[] { code + "%", "%" + filter + "%" });

		while (cursor.moveToNext()) {

			String id = cursor.getString(cursor.getColumnIndex("ID"));

			String name = cursor.getString(cursor.getColumnIndex("NAME"));

			String codeDb = cursor.getString(cursor.getColumnIndex("CODE"));

			Integer kind = cursor.getInt(cursor.getColumnIndex("KIND"));

			double longitude = cursor.getDouble(cursor
					.getColumnIndex("LONGITUDE"));

			double latitude = cursor.getDouble(cursor
					.getColumnIndex("LATITUDE"));

			String category = cursor.getString(cursor
					.getColumnIndex("CATEGORY"));

			String tel = cursor.getString(cursor.getColumnIndex("TEL"));

			String mobile = cursor.getString(cursor.getColumnIndex("MOBILE"));

			String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));

			String charge = cursor.getString(cursor.getColumnIndex("CHARGE"));

			beiJianDanWeis.add(new BeiJianDanWei(id, name, codeDb, null, null,
					null, address, kind, longitude, latitude, category, charge,
					tel, mobile));

		}

		if (cursor != null) {
			cursor.close();
		}

		return beiJianDanWeis;
	}


	public String queryEntMaxMotifyTime(String tableName, String column,
										String code) {

		String fieldName="CODE";
		if(tableName.equals("LINKMAN"))fieldName="REGION_CODE";
		String maxTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date(0));
		String  sql ="SELECT datetime("+column+") AS TIME1,ADDTIME AS TIME  from  "+tableName+" WHERE "+fieldName+" ||'' LIKE '" + code + "%'  ORDER BY TIME1 DESC LIMIT 0,1";
		Log.d("ent time sql",sql);
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(sql, null);

		while (cursor.moveToNext()) {

			String maxTimeRes = cursor.getString(cursor.getColumnIndex("TIME"));

			if (CharsetUtil.isNotNull(maxTimeRes)) {
				maxTime = maxTimeRes;
			}

		}

		if (cursor != null) {
			cursor.close();
		}

		return maxTime;
	}

	public void insertOrUpdateMoinitorPlanEnts(
			JSONArray list) {
		Log.d("rafe plan ent",String.valueOf(list));
		SQLiteDatabase db = getWritableDatabase();

		db.beginTransaction();

		for (int i=0;i<list.length();i++) {
			JSONObject plan=list.optJSONObject(i);
			String sql = "SELECT COUNT(*) FROM PLAN_ENT_IDS WHERE PID = ? AND ENT_ID=?";

			Cursor cursor = db.rawQuery(sql,
					new String[] { plan.optString("pid","0"), plan.optString("ent_id","0") });
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);

				ContentValues contentValues = new ContentValues();

				contentValues.put("PID", plan.optString("pid",""));
				contentValues.put("ENT_ID", plan.optString("ent_id",""));
				if (count > 0) {
					Log.d("rafe_MONITOR_PLAN——ent update",plan.optString("pid",""));
				} else {
					// 插入
					Log.d("rafe_MONITOR_PLAN——ent insert",plan.optString("pid",""));
					db.insert("PLAN_ENT_IDS", null, contentValues);
				}
			}

			if (cursor != null)
				cursor.close();
		}

		db.setTransactionSuccessful();

		db.endTransaction();

	}
	public void insertOrUpdateMobileSync(String code,String field) {

		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();



		ContentValues contentValues = new ContentValues();
		Date date = new Date();
		SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
		String LgTime = sdformat.format(date);
		contentValues.put(field, LgTime);
		db.update("MOBILE_SYN", contentValues, " CODE = ? ",
				new String[] { code });



		db.setTransactionSuccessful();

		db.endTransaction();

	}




	public    LinkMan queryLinkMan(String id) {

		LinkMan beiJianDanWei = new LinkMan();

		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.rawQuery(
				"SELECT * FROM LINKMAN  WHERE ID = ? ", new String[] { id });

		if (cursor.moveToNext()) {

			String regionCode = cursor.getString(cursor
					.getColumnIndex("REGION_CODE"));
			beiJianDanWei.setRegionCode(regionCode);
		}

		if (cursor != null) {
			cursor.close();

		}


		return beiJianDanWei;
	}

}